【Java】Date类,Calendar类

日期转字符串
字符串转日期
根据指定毫秒值创建日期

public class Date_Test1 {

	public static void main(String[] args) throws ParseException {
		
		Date date = new Date();
		System.out.println(date); //格林显示时间
		
		
		DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss SSS");
		//将时间 格式化为 字符串
		String str = format.format(date);
		System.out.println(str);
		
		String strDate = "2018-10-10 20:20:20";
		//将时间格式的字符串 转为 date
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date2 = df.parse(strDate);
		System.out.println(date2);
		
		//根据指定毫秒创建date
		Date date3 = new Date(1000);
		System.out.println(date3);
	}

}

毫秒与日期直接的互转

1、输入日期,转化为毫秒数:

	Calendar calendar = Calendar.getInstance();
    calendar.set(2019, 5, 11, 15, 8, 0);
    System.out.println(calendar.getTimeInMillis());

2、

	//要先转成Date格式,再getTime()
	String date = "2019-05-11 15-09-00";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    long time = simpleDateFormat.parse(date).getTime();
    System.out.println(time);

毫秒数转化为日期
1、

	long time = System.currentTimeMillis();//获取当前系统时间

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time);

    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
	System.out.println(year + "-" + (month + 1) + "-" + day + " "+ hour + ":" + minute + ":" + second);

2、

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long time = System.currentTimeMillis();
    date.setTime(time);
    System.out.println(simpleDateFormat.format(date));
发布了66 篇原创文章 · 获赞 45 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ACofKing/article/details/90110056