zoukankan      html  css  js  c++  java
  • 日期时间工具类

    本工具类主要内容是LocalDateTime与Date的互转以及与日期字符串的互转,可与commons-lang-xxx.jar中的DateUtils配合使用。

    import java.time.*;
    import java.time.format.DateTimeFormatter;
    import java.util.Date;
    
    public class DateTimeUtils {
        /**
         * 格式化LocalDateTime实例为日期时间字符串
         *
         * @param localDateTime
         * @param regex
         */
        public static String format(LocalDateTime localDateTime, String regex) throws Exception {
            return localDateTime.format(DateTimeFormatter.ofPattern(regex));
        }
    
        /**
         * 解析日期时间字符串为LocalDateTime实例
         *
         * @param str
         * @param regex
         */
        public static LocalDateTime parse(String str, String regex) throws Exception {
            return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(regex));
        }
    
        /**
         * Date实例转为LocalDateTime实例
         *
         * @param date
         */
        public static LocalDateTime Date2LocalDateTime(Date date) throws Exception {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
            System.out.println("localDateTime = " + localDateTime);
            return localDateTime;
        }
    
        /**
         * LocalDateTime实例转为Date实例,用到了Instant、ZoneId以及ZoneDateTime
         *
         * @param localDateTime
         */
        public static Date LocalDateTime2Date(LocalDateTime localDateTime) throws Exception {
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            System.out.println("date = " + date);
            return date;
        }
    }
  • 相关阅读:
    A. Dawid and Bags of Candies ( Codeforces Round #588 (Div. 2) )
    B. Ania and Minimizing (Codeforces Round #588 (Div. 2) )
    残缺的棋盘 (BFS)
    Max Sum (动态规划)
    高桥和低桥 (离散化 )
    White Sheet (矩形面积模板) (Codeforces Round #587 (Div. 3) )
    Catch That Cow (BFS luo搜 + 剪枝)
    Python笔记-字符串
    关于拖延症
    一些告诫
  • 原文地址:https://www.cnblogs.com/koushr/p/5873412.html
Copyright © 2011-2022 走看看