Java获取年月日

深藏阁楼爱情的钟 2023-10-18 19:53 105阅读 0赞
  1. public class TestMain {
  2. public static void main(String[] args) {
  3. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  4. // 1、普通的时间转换
  5. String string = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
  6. System.out.println(string);
  7. System.out.println("-------------------------------");
  8. // 2、日历类的时间操作
  9. Calendar calendar = Calendar.getInstance();
  10. System.out.println(calendar.get(Calendar.YEAR));
  11. System.out.println(calendar.get(Calendar.MONTH) + 1);
  12. System.out.println(calendar.get(Calendar.DATE));
  13. System.out.println("当前时间: " + dateFormat.format(calendar.getTime()));
  14. // 获取当前时间前3秒
  15. calendar.add(Calendar.SECOND, -3);// 3秒之前的时间
  16. System.out.println("当前时间3秒之前: " + dateFormat.format(calendar.getTime()));
  17. // 获取当前时间前3分钟
  18. calendar.add(Calendar.MINUTE, -3);// 3分钟之前的时间
  19. System.out.println("当前时间3分钟之前: " + dateFormat.format(calendar.getTime()));
  20. }
  21. }

输出:

  1. 2022-02-11
  2. -------------------------------
  3. 2022
  4. 2
  5. 11
  6. 当前时间: 2022-02-11 11:05:28
  7. 当前时间3秒之前: 2022-02-11 11:05:25
  8. 当前时间3分钟之前: 2022-02-11 11:02:25

发表评论

表情:
评论列表 (有 0 条评论,105人围观)

还没有评论,来说两句吧...

相关阅读

    相关 获取年月

    前言 需求:获取当前日期的前一个月份 当月有 31 天时,JS 日期对象 setMonth 问题 1. 一般做法 当前日期如果不是 31 号, 是没问题的,是