zoukankan      html  css  js  c++  java
  • Java中获取当前时间并格式化

    主要有以下方式,代码如下:

    1.使用Calendar

    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));

    2.使用Date

    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("当前时间:" + sdf.format(d));

    3.使用jdk8新的时间api,LocalDateTime、LocalDate、LocalTime

    ① jdk8 日期与时间:LocalDateTime

    LocalDateTime nowDateTime = LocalDateTime.now();
    System.out.println(nowDateTime);
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(dateTimeFormatter.format(nowDateTime));
    // 反着使用也可以
    System.out.println(nowDateTime.format(dateTimeFormatter));

    ②jdk8 日期: LocalDate

    LocalDate nowDate = LocalDate.now();
    System.out.println(nowDate);
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    System.out.println(dateFormatter.format(nowDate));
    // 反着使用也可以
    System.out.println(nowDate.format(dateFormatter));

    ③jdk8 时间:LocalTime

    LocalTime nowTime = LocalTime.now();
    System.out.println(nowTime);
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    System.out.println(timeFormatter.format(nowTime));
    // 反着使用也可以
    System.out.println(nowTime.format(timeFormatter));
  • 相关阅读:
    2.8 Classes of Restricted Estimators
    navicat远程登录windows服务器
    面试题
    【南阳OJ分类之语言入门】80题题目+AC代码汇总
    基于‘BOSS直聘招聘信息’分析企业到底需要什么样的PHPer
    数据开源
    Pyhton爬虫实战
    Python爬虫框架Scrapy实战
    做网站用UTF-8编码还是GB2312编码?
    【南阳OJ分类之大数问题】题目+AC代码汇总
  • 原文地址:https://www.cnblogs.com/convict/p/8759014.html
Copyright © 2011-2022 走看看