Java中的日期转换(String转Date、Date转String以及日期格式转换)

1. String转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();
}

注意: String和DateFormat样式需一样,不然无法解析

2. Date转String

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

3. 常见应用场景

在项目中,我们常常需要从数据库中查询出日期,然后转换为一定格式的日期进行数据处理,比如:我们需要统计指标的完成率,一类指标不止一条,但是只要上报一条就算这类指标已上报,我们需要把日期和指标的类别拼接起来进行去重。

	/**
     * 指标监控:查询分公司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;
    }
发布了19 篇原创文章 · 获赞 4 · 访问量 1564

猜你喜欢

转载自blog.csdn.net/DATANGguanjunhou/article/details/104286542