【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));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值