如何在Java中获得DateTime的整数值? 我在Java项目中工作,我需要在Java中获得DateTime的数字“值”。例如:DateTime是2020-07-22T17:40:56.235+05:30,我想将其转换为

问题描述 投票:0回答:1
。我正在使用

20200722174056235

DateTime
getDate()
来使这种值。
有任何方法或任何方法将日期时间掩盖到这样的数字值中?
getYear()
我需要只使用joda
DateTime calendar = new DateTime();

        int year       = calendar.getYear();
        int month      = calendar.getMonthOfYear();
        int dayOfMonth = calendar.getDayOfMonth();            
        int hour       = calendar.getHourOfDay();// 12 hour clock
        int minute     = calendar.getMinuteOfHour();
        int second     = calendar.getSecondOfMinute();
        int millisecond= calendar.getMillisOfSecond();
       
        String dt = String.valueOf((year)+
                String.valueOf(month)+
                String.valueOf(dayOfMonth)+
                String.valueOf(hourOfDay)+
                String.valueOf(minute)+
                String.valueOf(second)+
                String.valueOf(millisecond));
        return Long.valueOf(dt);

使用一个格式
DateTime
当我现在在时区域中运行代码时,输出输出:

20200722210458862

java datetime jodatime date-formatting
1个回答
5
投票
仅在我期望经常调用的库方法以及效率可能引起关注的情况下,我可能会考虑不格式化和解析字符串。以下给出相同的结果。

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmssSSS"); DateTime calendar = new DateTime(); String formatted = calendar.toString(formatter); Long numericValue = Long.parseLong(formatted); System.out.println(numericValue);

did您的代码工作?

您的代码可能仅将一位数的值格式化为字符串中的一个字符,因此您的字符串通常太短而错过了一些零。例如:

long numericValue = calendar.getYear(); numericValue = numericValue * 100 + calendar.getMonthOfYear(); numericValue = numericValue * 100 + calendar.getDayOfMonth(); numericValue = numericValue * 100 + calendar.getHourOfDay(); numericValue = numericValue * 100 + calendar.getMinuteOfHour(); numericValue = numericValue * 100 + calendar.getSecondOfMinute(); numericValue = numericValue * 1000 + calendar.getMillisOfSecond();

代码段

Correct: 20200722210458862 (2020 07 22 21 04 58 862) From your code: 202072221458862 (2020 7 22 21 4 58 862)


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.