• 线程安全的LocalDateTime的各种转换


    1.将LocalDateTime转为自定义的时间格式的字符串

    public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

      return localDateTime.format(formatter);

    }

    2.将long类型的timestamp转为LocalDateTime

    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {

       Instant instant = Instant.ofEpochMilli(timestamp);

      ZoneId zone = ZoneId.systemDefault();

      return LocalDateTime.ofInstant(instant, zone);

    }

    3.将LocalDateTime转为long类型的timestamp

      public static long getTimestampOfDateTime(LocalDateTime localDateTime) {

      ZoneId zone = ZoneId.systemDefault();

      Instant instant = localDateTime.atZone(zone).toInstant();

      return instant.toEpochMilli();

    }

    4.将某时间字符串转为自定义时间格式的LocalDateTime

    public static LocalDateTime parseStringToDateTime(String time, String format) {

      DateTimeFormatter df = DateTimeFormatter.ofPattern(format);

      return LocalDateTime.parse(time, df);

    }

    5.附一个获取当日凌晨时间戳的方式

    @Test
    public void testSystem(){
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    long timeInMillis = c.getTimeInMillis();
    Instant instant = Instant.ofEpochMilli(timeInMillis);
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String format = format.format( localDateTime);
    System.out.println(format);
    }

    最后看懂这个代码, 就提升了
    long now = System.currentTimeMillis() / 1000l;

    long daySecond = 60 * 60 * 24;

    long dayTime = now - (now + 8 * 3600) % daySecond;

    long nowTime =System.currentTimeMillis();
    long todayStartTime =nowTime - ((nowTime + TimeZone.getDefault().getRawOffset()) % (24 * 60 * 60 * 1000L));



  • 相关阅读:
    shell——变量
    xxx is not in the sudoers file.This incident will be reported.的解决方法
    百度面试回忆
    iOS网络协议 HTTP/TCP/IP浅析
    使用xib封装一个自定义view的步骤
    修改了系统自带头文件后,Xcode会报错
    字典转模型规范化
    文本属性Attributes
    苹果API常用英语名词
    命令行 -- 命令"%cd%"
  • 原文地址:https://www.cnblogs.com/binyue-sunmk/p/12785488.html
Copyright © 2020-2023  润新知