• Java中Calendar/SimpleDateFormat/Date常用方法总结


     1 //获取当前时刻yyyy-MM-dd HH:mm:ss
     2 Calendar calendar = Calendar.getInstance();
     3 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
     4 String now = sdf.format(calendar.getTime());
     5 System.out.println(now);
     6 
     7 //获取当前时刻yyyy-MM-dd
     8 Calendar calendar = Calendar.getInstance();
     9 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
    10 String now1 = sdf1.format(calendar.getTime());
    11 System.out.println(now1);
    12 
    13 //获取当前时刻yyyy-MM
    14 Calendar calendar = Calendar.getInstance();
    15 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");// 设置日期格式
    16 String now2 = sdf2.format(calendar.getTime());
    17 System.out.println(now2);
    18 
    19 //获取当前时刻,年月日
    20 Calendar calendar = Calendar.getInstance();
    21 int year = calendar.get(Calendar.YEAR);
    22 int month = calendar.get(Calendar.MONTH) + 1;
    23 int day = calendar.get(Calendar.DAY_OF_MONTH);
    24 System.out.println(year + "-" + month + "-" + day);
    25 
    26 //获取当前时刻时间戳
    27 Calendar calendar = Calendar.getInstance();
    28 long ts = calendar.getTimeInMillis();
    29 System.out.println(ts);
    30 
    31 //获取上个月yyyy-MM
    32 Calendar calendar = Calendar.getInstance();
    33 calendar.add(Calendar.MONTH, -1);
    34 String lastMonth = new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
    35 System.out.println(lastMonth);
    36 
    37 //获取昨天yyyy-MM-dd
    38 Calendar calendar = Calendar.getInstance();
    39 calendar.add(Calendar.DATE, -1);
    40 String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
    41 System.out.println(yesterday);
    42 
    43 //将指定年月日时分秒转换成时间戳
    44 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    45 Date date = simpleDateFormat.parse("2015-05-01 00:00:00");
    46 long ts1 = date.getTime();
    47 System.out.println(ts1);
    48 //或者
    49 Calendar calendar = Calendar.getInstance();
    50 calendar.set(2015, 4, 1, 0, 0, 0);     //此处4即代表5月
    51 long ts2 = calendar.getTimeInMillis();
    52 System.out.println(ts2);
    53 
    54 //将指定时间戳转化为年月日时分秒
    55 SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
    56 long ts = 1234567899L;
    57 String date = format.format(ts);
    58 Date date1 = format.parse(date);
    59 System.out.println("Format To String(Date):" + date);
    60 System.out.println("Format To Date:" + date1);
  • 相关阅读:
    Mesh简介
    不区分大小写字符串比较函数
    python3.5.4安装时老是弹出api-ms-win-crt-runtime-|1-1-0.dll错误的解决方法
    如何在SVN创建分支版本
    Sublime使用小技巧——去掉.dump后缀
    STM32F407串口调试总结
    USB学习笔记
    实验四+005+陈晓华
    实验三+005+陈晓华
    第5次作业+005+陈晓华
  • 原文地址:https://www.cnblogs.com/sunseine/p/4493942.html
Copyright © 2020-2023  润新知