java将日期中的斜线或中文改成统一日期格式 yyyy-MM-dd HH:mm:ss

虾米姐 阅读:1465 2020-06-07 11:11:10 评论:0

前言

最近在优化代码方面,因为之前在字符串中截取日期,日期的格式样式不统一。

日期格式

2019/6/14 14:00:00
2019/03/4 1:00:00
2019年8月4日12:00

要求改成统一格式 :
2019-06-08 12:00:00

把斜线改成横线

	   // 斜线变成横线格式 
       String strDate = "2019/6/14 14:00"; // 传入的日期  
       Date str = DateUtil.stringToDate(strDate.replace("/", "-", DateExtendUtil.FULL); 
 
	   // 中文改成横线格式 
       String strDate = "2019年6月14日 14:00 "; // 传入的日期  
	   String str = strDate.replaceAll("[年,月]", "-"); 
	   Date str = DateUtil.stringToDate(str.replace("[日]", "-"+ ":00" , DateExtendUtil.FULL); 

时间处理类

public class DateExtendUtil extends DateUtil { 
    public static final String FULL = "yyyy-MM-dd HH:mm:ss"; 
    private static final long ONE_DAY = 24 * 60 * 60 * 1000L; 
     
    public static Date stringToDate(String strDate, String formartStr) { 
        Date date = null; 
        if (formartStr != null && !"".equals(formartStr)) { 
            SimpleDateFormat sdf = new SimpleDateFormat(formartStr); 
            try { 
                date = sdf.parse(strDate); 
            } catch (Exception ignored) { 
            } 
        } 
 
        return date; 
    } 
} 
标签:java
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号