java中系统时间格式化

java中系统默认时间是用与时间点(1970 年 1 月 1 日,00:00:00 GMT)之间的毫秒数表示,是一个long值

所以如果我们想看到年月日,时分秒这种类型的时间格式必须将其格式化

本文中举个例子来说明一下:

事情是这样的,我用File在D盘下创建一个了文件123.txt,然后用file.lastModified()来获取它最后一次修改时间,但是输出后发现这个值是一个long型的值:1532423965661这样式的,查了api才发现这是这个时间到1970 年 1 月 1 日,00:00:00 之间的毫秒数。所以必须将其格式化才能看到我们熟悉的这种时间:2018年7月24日 下午05时19分25秒。所以我就搞了一下下,好了话不多说直接上代码。文中分别有两种格式化方式,均可实现。

方法一:SimpleDateFormat实现

方法一:DateFormat实现

package com.xintouyun.Filetest;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class date {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File file=new File("d:/123.txt");
		file.createNewFile();
		System.out.println("文件123.txt最后修改日期为:"+file.lastModified());
		String result=getFormatDate_2(file.lastModified());
		System.out.println("文件123.txt最后修改日期为:"+result);
		
	}
	public static String getFormatDate_1(Long lo) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String s=sdf.format(lo);
		return s;
		}
	public static String getFormatDate_2(Long lo) {
		DateFormat df=DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
		String s=df.format(lo);
		return s;
	}
}

两种方式运行结果分别为:

方法一:

文件123.txt最后修改日期为:1532423965661
文件123.txt最后修改日期为:2018-07-24 17:19:25

方法二:

文件123.txt最后修改日期为:1532423965661
文件123.txt最后修改日期为:2018年7月24日 下午05时19分25秒

大家可以根据自己需求随意使用。

猜你喜欢

转载自blog.csdn.net/qq_40180411/article/details/81187919
今日推荐