Date conversion in Java (String turn Date, Date turn String and date format)

1. String turn Date

//将String转换为Date
String dateString = "2020-02-12 20:55:09";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
	date = df.parse(dateString);
} catch (ParseException e) {
	e.printStackTrace();
}

Note: String DateFormat and styles as needed, or could not be resolved

2. Date turn String

//将Date转换为String
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);

3. Common scenarios

In the project, we often need to query from the database the date, and then converted to a date certain for data processing formats, such as: we need to complete the rate of statistical indicators, a class of more than one index, but as long as a report even if such indicators report, we need to put the category and date indicators to be re-spliced ​​together.

	/**
     * 指标监控:查询分公司30天内上报的指标数量
     *
     * @return 各分公司30天内上报的指标数量的list集合
     */
    @Override
    public List<Integer> queryKpiTrendMonth() {
    	//从数据库查询分公司的id
        List<Integer> bcList = monitorStatisticsMapper.queryBcId();
        //从数据库查询30天内的指标
        List<KpiEntity> kpiEntityList = monitorStatisticsMapper.queryKpiTrendMonth();
        //创建一个数组存放各分公司30天内总的指标数量
        ArrayList<Integer> kpiCount = new ArrayList<>();
        for (int i = 0; i < bcList.size(); i++) {
            String bcId = bcList.get(i).toString();
            int count = 0;
            //利用set元素不可重复的特性去重,统计指标数量
            HashSet<String> set = new HashSet<>();
            for (int j = 0; j < kpiEntityList.size(); j++) {
                if (kpiEntityList.get(j).getBcId().equals(bcId)) {
                	//日期转换,String(包含时分秒的时间)→Date→String(不包含时分秒的时间)
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = null;
                    try {
                        date = df.parse(kpiEntityList.get(j).getKpiTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = sdf.format(date);
                    String s = dateString + kpiEntityList.get(j).getKpiId();
                    set.add(s);
                    count = set.size();
                }
            }
            kpiCount.add(count);
        }
        return kpiCount;
    }
Published 19 original articles · won praise 4 · Views 1564

Guess you like

Origin blog.csdn.net/DATANGguanjunhou/article/details/104286542