【 格式化时间(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;


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM