【 格式化时间(SimpleDateFormat)用法】

将特定字符串转换成Date格式

可以通过 new 一个 SimpleDateFormat 对象,通过对象调用parse方法实现

示例代码:

String time = "2019-11-09";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dateTime = null;
try {
    dateTime = simpleDateFormat.parse(time);
} catch (ParseException e) {
    e.printStackTrace();
}

将Date格式转化成特定字符串

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main{
    public static void main(String[] args){
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        System.out.println(sdf.format(date));
    }
}

注意:SimpleDateFormat 12小时制和24小时制的区别

使用SimpleDateFormat时格式化时间的 yyyy.MM.dd 为年月日;
如果希望格式化时间为12小时制的,则使用hh:mm:ss;
而如果希望格式化时间为24小时制的,则使用HH:mm:ss;

猜你喜欢

转载自www.cnblogs.com/KeepZ/p/11826502.html