有效地将长格式yyyyMMddHHmmss的DateTime转换为另一个区域以进行比较

问题描述

我有一个长值,它代表一个类似20200319234500的日期时间(转换为2020年3月19日晚上11:45:00) 我希望将此长值(20200319234500)再次以长格式转换为另一个时区,以便与本地时区中的当前日期时间进行大于或小于比较。

我想高效地做到这一点,所以我不必在运行时创建任何对象,也不必在启动后创建字符串。 但是看来我必须先将长时间转换为字符串,然后调用zoneddatetime.parse()函数获取日期时间,然后进行比较。还有另一种方法吗?

 //This is kNown at compile time
        ZoneId baseZone = ZoneId.of("Europe/Paris");
        //This is kNown at compile time
        ZoneId localZone = ZoneId.of("America/New_York");
        //This is kNown at compile time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss").withZone(baseZone);

        long baseDateTime = 20210321234500L;

        //Dont want o be doing string operations. Is there a way to keep it in long and get another long in a different zone?
        zoneddatetime convertedBaseDateTime  = zoneddatetime.parse(Long.toString(baseDateTime),formatter);
        //Can I just get a long that represents current time in local zone? local zone is not JVM zone
        zoneddatetime localDateTime = zoneddatetime.Now(localZone);
        //Thats the only operation I want to perform
        boolean result = convertedBaseDateTime.isBefore(  localDateTime);

解决方法

您可以做一些数学运算以获取年,月,日,小时。分钟,长一点,然后您可以将其传递给ZonedDateTime.of

long baseDateTime = 20210321234500L;
int year = (int)(baseDateTime / 10000000000L);
int month = (int)(baseDateTime / 100000000L % 100);
int day = (int)(baseDateTime / 1000000L % 100);
int hour = (int)(baseDateTime / 10000L % 100);
int minute = (int)(baseDateTime / 100L % 100);
int second = (int)(baseDateTime % 100);
ZonedDateTime convertedBaseDateTime = ZonedDateTime.of(year,month,day,hour,minute,second,baseZone);

这不会创建新的字符串。

此后,请注意,如果您只想检查日期时间是否在“现在”之前,则不需要“现在”区域。您只需要比较从那时到现在的(milli / nano)秒数。

// don't need these
// ZoneId localZone = ZoneId.of("America/New_York");
// ZonedDateTime localDateTime = ZonedDateTime.now(localZone);

// you just need to compare
convertedBaseDateTime.toEpochSecond() * 1000 < System.currentTimeMillis()

也就是说,如果性能对您如此重要,那么也许您不应该使用Java,而应该使用更底层的语言。

,

long baseDateTime = 20210321234500L; LocalDateTime time = LocalDateTime.ofEpochSecond(baseDateTime /1000,ZoneOffset.ofHours(8)); //然后您可以使用time2.isAfter()或其他可比较的方法连接到jdk 8 API。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...