Java获取当前时间年月日的方法

Java获取当前时间年月日的方法

public static void main(String[] args) throws ParseException {
    Calendar now = Calendar.getInstance();
    System.out.println("年: " + now.get(Calendar.YEAR));
    System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");
    System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
    System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
    System.out.println("分: " + now.get(Calendar.MINUTE));
    System.out.println("秒: " + now.get(Calendar.SECOND));
    System.out.println("当前时间毫秒数:" + now.getTimeInMillis());
    System.out.println(now.getTime());

    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateNowStr = sdf.format(d);
    System.out.println("格式化后的日期:" + dateNowStr);

    String str = "2022-09-13 17:26:33"; //要跟上面sdf定义的格式一样
    Date today = sdf.parse(str);
    String dateNowStr1 = sdf.format(today);
    System.out.println("格式化后的日期:" + dateNowStr1);


    String str1 = "2012-1-13 17:26:33"; //要跟上面sdf定义的格式一样
    Date today1 = sdf.parse(str1);
    System.out.println("字符串转成日期:" + today1);
}
: 2022: 10: 14: 17: 3: 1
当前时间毫秒数:1665738181754
Fri Oct 14 17:03:01 CST 2022
格式化后的日期:2022-10-14 17:03:01
格式化后的日期:2022-09-13 17:26:33
字符串转成日期:Fri Jan 13 17:26:33 CST 2012

Process finished with exit code 0

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值