java中将时间格式转换

java中将时间格式转换

Date格式的数据和String格式。
获取当前时间 new Date()
将时间转换为自己想要的格式可以用 SimpleDateFormat
SimpleDateFormat有两个方法format(),parse()。
format()将时间转换为字符串,parse()是将字符串转换为时间格式。(按照自己定义的时间格式 “yyyy-MM-dd” 或者其它)


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2021-07-23 13:45:34";
System.out.println(sdf.format(new Date()));//时间格式转字符串
System.out.println(new SimpleDateFormat("yyyy-MM-dd").prase(date));//字符串格式转时间格式(prase方法需要try/catch或者throws ParseException)

获取的时间格式如下:
在这里插入图片描述
SimpleDateFormat()获取想要的时间数据

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /*四位数表示年*/
    SimpleDateFormat year = new SimpleDateFormat("yyyy");

    /*两位数表示年保留后面两位*/
    SimpleDateFormat yearLast = new SimpleDateFormat("yy");

    /*今天是一年中的第几月*/
    SimpleDateFormat month = new SimpleDateFormat("MM");

    /*今天是一月中第几天 */
    SimpleDateFormat dayOfMonth = new SimpleDateFormat("dd");

    /*今天是一年中的第几天*/
    SimpleDateFormat dayOfYear = new SimpleDateFormat("DD");

    /*当前小时(24小时时间制) */
    SimpleDateFormat HH = new SimpleDateFormat("HH");

    /*当前小时(12个小时时间制)*/
    SimpleDateFormat hh = new SimpleDateFormat("hh");

    /*当前小时的第多少分钟*/
    SimpleDateFormat mm = new SimpleDateFormat("mm");

    /*获取当前秒*/
    SimpleDateFormat ss = new SimpleDateFormat("ss");

    System.out.println(sdf.format(new Date()));
    System.out.println(year.format(new Date()));
    System.out.println(yearLast.format(new Date()));
    System.out.println(month.format(new Date()));
    System.out.println(dayOfMonth.format(new Date()));
    System.out.println(dayOfYear.format(new Date()));
    System.out.println(HH.format(new Date()));
    System.out.println(hh.format(new Date()));
    System.out.println(mm.format(new Date()));
    System.out.println(ss.format(new Date()));

输出结果:
输出结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值