欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java时间戳转时间,获取一天的最大时间、最小时间,时间格式化

程序员文章站 2022-06-09 16:03:07
...
  1. 时间格式化
    1.         //获取当前日期时间并按要求格式化,注意yyyyMMdd的大小写格式,大小写不一样,输出的结果也不一样
              SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
              SimpleDateFormat format2 = new SimpleDateFormat("HHmmss");
              String date = format1.format(new Date());
              String time = format2.format(new Date());
              System.out.println("date:  "+ date +"   time:   "+ time);

       

  2. 获取系统时间戳
    1. Long stamp1 = System.currentTimeMillis();//13位的时间戳,格式化后:2019-12-30 18:18:24.000
      Long stamp2 = System.currentTimeMillis()/1000;//10位的时间戳,格式化后:2019-12-30 18:18:24

       

  3. 获取一天的最大时间、最小时间
    public static Long getDailyStartTime(Long timeStamp, String timeZone) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
            calendar.setTimeInMillis(timeStamp);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar.getTimeInMillis();
        }
    
        public static Long getDailyEndTime(Long timeStamp, String timeZone) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
            calendar.setTimeInMillis(timeStamp);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            return calendar.getTimeInMillis();
        }
    
    Long start = getDailyStartTime(System.currentTimeMillis(),"GMT+8:00");//一天的最早时间
    Long end = getDailyEndTime(System.currentTimeMillis(),"GMT+8:00");//一天的最晚时间