简体   繁体   English

如何将字符串输入转换为毫秒到Date

[英]How to convert String input with milliseconds to Date

I have a java method which needs to convert a Date from one input String format to another. 我有一个java方法,需要将Date从一个输入String格式转换为另一个。 The input and output formats must retain all millisecond detail, as this is for a process tracking solution where timestamps will often be just milliseconds apart. 输入和输出格式必须保留所有毫秒细节,因为这是针对过程跟踪解决方案的,其中时间戳通常仅相隔几毫秒。

The SimpleDateFormat seems to be losing all millisecond data, and just returning random numbers for the seconds and milliseconds. SimpleDateFormat似乎正在丢失所有毫秒数据,只返回秒和毫秒的随机数。

input date String: "05/23/2013 12:32:13.45133" input date format: "MM/dd/yyyy HH:mm:ss.SSSSS" output date format: "yyyyMMddHHmmssSSS" 输入日期字符串:“05/23/2013 12:32:13.45133”输入日期格式:“MM / dd / yyyy HH:mm:ss.SSSSS”输出日期格式:“yyyyMMddHHmmssSSS”

Given the above input date and format, my resulting Date String is: 20130523123258133. This is obviously completely off from the input seconds. 鉴于上面的输入日期和格式,我得到的日期字符串是:20130523123258133。这显然完全取决于输入秒。

The input format may vary, but the output format must always be the same. 输入格式可能不同,但输出格式必须始终相同。

Below is the current method: 以下是当前的方法:

private long dateSequencer(String inputDt, String inputFormat) {
    long result = 0;
    try {
        // Convert input date into yyyyMMddHHmmssSSS format for sequencing
        SimpleDateFormat dtFrmt = new SimpleDateFormat(inputFormat);
        Date dt = new Date();
        dt = dtFrmt.parse(inputDt);
        // input String converted to Date, now reformat to Long
        dtFrmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String reFrmt = dtFrmt.format(dt);
        result = Long.parseLong(reFrmt);
    } catch (Exception ex) {
        System.out.println("++++ Exception converting dateSequencer: " + ex.toString());
    }
    System.out.print("+++ABM dateSeq: [inputDt=" + inputDt + "] [inputFormat=" + inputFormat + "] [result=" + result +"]");
    return result;
}

Log file entry from runtime: 运行时的日志文件条目:

+++ABM dateSeq: [inputDt=05/23/2013 12:32:13.45133] [inputFormat=MM/dd/yyyy HH:mm:ss.SSSSS] [result=20130523123258133]

Since the input format may change, I cannot manually parse the input String to rely on a specific pattern. 由于输入格式可能会改变,我无法手动解析输入String以依赖特定模式。 This is why I am allowing the pattern to be passed, and using a SimpleDateFormat to convert to Date, then back to String. 这就是为什么我允许传递模式,并使用SimpleDateFormat转换为Date,然后返回String。

How can I do this, reliably? 我怎么能可靠地做到这一点? Is there a more efficient way to convert a given input Date string, to a standard format? 有没有更有效的方法将给定的输入日期字符串转换为标准格式?

Thanks! 谢谢!

If you can assume that in every case month, day, minute, second have 2 digits, year has 4 digits and milliseconds have 3 digits and just the pattern differs, you can simply do the following: 如果您可以假设在每种情况下月,日,分,秒都有2位数,年份有4位数,毫秒有3位数,只是模式不同,您可以简单地执行以下操作:

public static long convert(String inputDt, String inputFormat) {
    int dd = inputFormat.indexOf("dd");
    int MM = inputFormat.indexOf("MM");
    int yyyy = inputFormat.indexOf("yyyy");
    int HH = inputFormat.indexOf("HH");
    int mm = inputFormat.indexOf("mm");
    int ss = inputFormat.indexOf("ss");
    int SSS = inputFormat.indexOf("SSS");
    return Long.valueOf(inputDt.substring(yyyy,yyyy+4) + inputDt.substring(MM, MM+2) + inputDt.substring(dd, dd+2) + inputDt.substring(HH, HH+2)
            + inputDt.substring(mm, mm+2) + inputDt.substring(ss, ss+2) + inputDt.substring(SSS,SSS+3));        
}

convert("05/23/2013 12:32:13.133", "MM/dd/yyyy HH:mm:ss.SSS") yields 20130523123213133

Your input date String: "05/23/2013 12:32:13.45133" contains 5 digits for milliseconds. 您的输入日期字符串:“05/23/2013 12:32:13.45133”包含5位数字,以毫秒为单位。 And It's not possible... There must be 3 digits. 这是不可能的...必须有3位数。 So 45133 milliseconds is equals to 45 seconds and 133 millis. 所以45133毫秒等于45秒和133毫秒。 Your input date string is the date "05/23/2013 12:32:58.133" 您输入的日期字符串是日期“05/23/2013 12:32:58.133”

java.time java.time

The modern approach uses the java.time classes that years ago supplanted the troubled old classes such as Date & Calendar & SimpleDateFormat . 现代方法使用java.time类, 这些类几年前取代了陷入困境的旧类,如DateCalendarSimpleDateFormat No need to ever touch those terrible legacy classes again. 无需再次触及那些可怕的遗产类。

Define a formatting pattern to suit your input with the DateTimeFormatter class. 使用DateTimeFormatter类定义格式模式以适合您的输入。

String input = "05/23/2013 12:32:13.45133"
DateTimeFormatter formatterInput = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss.SSSSS" );
LocalDateTime ldt = LocalDateTime.parse( input , formatterInput );

DateTimeFormatter formatterOutput = DateTimeFormatter.ofPattern( "uuuuMMddHHmmssSSS" );
String output = ldt.format( formatterOutput );

System.out.println( ldt );
System.out.println( output );

ISO 8601 ISO 8601

By the way, your desired output format happens to be close to the standard ISO 8601 format. 顺便说一句,您想要的输出格式恰好接近标准的ISO 8601格式。 The “basic” versions in the standard minimize the use of delimiters: YYYY-MM-DDTHH:MM:SS.S versus YYYYMMDDTHHMMSS.S as you have done. 标准中的“基本”版本最小化分隔符的使用:YYYY-MM-DDTHH:MM:SS.S与YYYYMMDDTHHMMSS.S一样。

I suggest you make a practice of using the standard format rather than inventing your own. 我建议你练习使用标准格式,而不是发明自己的格式。 To comply, add the T between the date portion and the time portion. 为了符合要求,在日期部分和时间部分之间添加T


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用符合JDBC 4.2或更高版本的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM