简体   繁体   English

如何将格式日期“MMddhhmmss”转换为“yyyy-MM-dd HH:mm:ss”?

[英]How to convert format date “MMddhhmmss” to “yyyy-MM-dd HH:mm:ss”?

How to convert calendar date to yyyy-MM-dd HH:mm:ss format.如何将日历日期转换为 yyyy-MM-dd HH:mm:ss 格式。

protected String paymentDatetime (String transmissionDateTime){
    long transactionDateTime = System.currentTimeMillis();
    Date now = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        SimpleDateFormat df = new SimpleDateFormat("MMddhhmmss");
        Calendar nowDate = Calendar.getInstance();
        nowDate.setTime(now);

        Calendar transmissionDate = Calendar.getInstance();
        transmissionDate.setTime(df.parse(transmissionDateTime));
        transmissionDate.set(Calendar.YEAR, nowDate.get(Calendar.YEAR));

        transactionDateTime = transmissionDate.getTime().getTime();
    } catch (ParseException e) {
        LOGGER.error("cannot parse transmission date time : " + transmissionDateTime);
    }
    return sdf.format(transactionDateTime);
}

I want to get the value thrown by String transmissionDateTime , but in fact when I throw the value = 1707 1255 17 (in AM) will be convert to "2020-07-17 00:55:17".我想得到String transmissionDateTime抛出的值,但实际上当我抛出 value = 1707 1255 17 (in AM) 时,将转换为“2020-07-17 00:55:17”。 How to convert so that every 12.00 or 00.00 (12 o'clock) both AM and PM don't change?如何转换以使 AM 和 PM 每隔 12.00 或 00.00(12 点)都不会改变?

Do not handle dates and times as strings in your program.不要在程序中将日期和时间作为字符串处理。 Handle and store them as proper date-time objects.处理并将它们存储为适当的日期时间对象。 When you take string input, parse it to a date-time object.当您输入字符串时,将其解析为日期时间 object。 Only when you need to give string output, format your date-time object into an appropriate string.仅当您需要提供字符串 output 时,将您的日期时间 object 格式化为适当的字符串。

java.time java.time

I think that your parsing becomes clearer with java.time, the modern Java date and time API.我认为使用 java.time,现代 Java 日期和时间 API,您的解析会变得更加清晰。 I understand that the hour given in the string is hour of day, so 00 means 12 midnight and 12 means 12 noon.我知道字符串中给出的小时是一天中的小时,所以 00 表示午夜 12 点,12 表示中午 12 点。

    Year thisYear = Year.now(ZoneId.systemDefault());
    DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
            .appendPattern("ddMMHHmmss")
            .parseDefaulting(ChronoField.YEAR, thisYear.getValue())
            .toFormatter();
    
    String transmissionDateTimeString = "1707125517";
    
    LocalDateTime transmissionDateTime
            = LocalDateTime.parse(transmissionDateTimeString, inputFormatter);
    
    System.out.println(transmissionDateTime);

Output when running today: Output 今天运行时:

2020-07-17T12:55:17 2020-07-17T12:55:17

Formatting output格式化 output

I am showing you two options for formatting output as 2020-07-17 12:55:17 .我向您展示了将 output 格式化为2020-07-17 12:55:17的两个选项。

  1. Use a formatter使用格式化程序
  2. Simply replace the T with a space只需将T替换为空格

Use a formatter:使用格式化程序:

    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String output = transmissionDateTime.format(outputFormatter);

Simply replace the T :只需更换T

    String output = transmissionDateTime.toString().replace('T', ' ');

What went wrong in your code?你的代码出了什么问题?

Lower case hh in a format pattern string is for hour within AM or PM from 01 through 12. This goes for both the old-fashioned SimpleDateFormat and for the modern DateTimeFormatter .格式模式字符串中的小写hh是上午或下午从 01 到 12 的小时。这适用于老式的SimpleDateFormat和现代的DateTimeFormatter You didn't tell the formatter whether you wanted AM or PM.您没有告诉格式化程序您想要上午还是下午。 In this case SimpleDateFormat assumes AM, which is why you got a time og 00:55:17.在这种情况下, SimpleDateFormat假定 AM,这就是为什么您的时间为 00:55:17。 Upper case HH is for hour of day from 00 through 23.大写HH表示一天中从 00 到 23 的小时。

It furthermore seems that you have accidentally swapped month and day of month in your format pattern for parsing, MMddhhmmss .此外,您似乎不小心在格式模式中交换了月份和日期以进行解析MMddhhmmss When I called your method, I got 2020-05-07 00:55:17 .当我调用你的方法时,我得到了2020-05-07 00:55:17 Month and day of month are wrong.月份和日期是错误的。 Your df parsed 1707125517 into Fri May 07 00:55:17 CET 1971 .您的df 1707125517解析为Fri May 07 00:55:17 CET 1971 There is no 17th month of the year, but SimpleDateFormat confusingly extrapolates, so the 17th month of 1970 becomes the 5th month of 1971.一年中没有第 17 个月,但SimpleDateFormat令人困惑地推断,因此 1970 年的第 17 个月变成了 1971 年的第 5 个月。

Links链接

Calendar and SimpleDateFormat are old classes and no longer recommended. CalendarSimpleDateFormat是旧类,不再推荐。
Use the LocalDateTime and DateTimeFormatter classes in the java.time package.使用java.time package 中的LocalDateTimeDateTimeFormatter类。

DateTimeFormatter from = DateTimeFormatter.ofPattern("MMddhhmmss");
DateTimeFormatter to12Hour = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
DateTimeFormatter to24Hour = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(from));
System.out.println(ldt.format(to12Hour));
System.out.println(ldt.format(to24Hour));

Prints印刷

0716082236
2020-07-16 08:22:36 PM
2020-07-16 20:22:36

As already covered by a comment : MMddhhmmss should be MMddHHmmss using uppercase HH .正如评论已经涵盖的那样: MMddhhmmss应该是使用大写HHMMddHHmmss


String "1707125517" with format MMddHHmmss means MM = 17 and dd = 07 .格式MMddHHmmss的字符串"1707125517"表示MM = 17dd = 07 When parsed without a year, the year defaults to 1970, and month 17 of the year 1970 resolves to month 5 of the year 1971, which is why the question code results in 2020-05-07 (month 5, day 7).不带年份解析时,年份默认为 1970 年,1970 年的第 17 个月解析为 1971 年的第5个月,这就是问题代码导致2020-05-07 (第 5 个月第 7 天)的原因。

Are you sure the input with Month = 17 is what you want to parse, and that the format pattern is what you intended?您确定 Month = 17 的输入是您要解析的内容,并且格式模式是您想要的吗? Seems that month and day are flipped, given you said "will be convert to "2020-07-17 00:55:17"" , where month is 7 and day is 17, so perhaps you should try format ddMMHHmmss instead .似乎月份和日期是颠倒的,因为你说"will be convert to "2020-07-17 00:55:17"" ,其中月份是 7 天是 17,所以也许你应该尝试格式化ddMMHHmmss

The method in the question can be shortened to use only one Calendar object instead of two:问题中的方法可以缩短为仅使用一个Calendar object 而不是两个:

protected static String paymentDatetime(String dateTime) {
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    try {
        cal.setTime(new SimpleDateFormat("ddMMHHmmss").parse(dateTime));
    } catch (ParseException e) {
        throw new IllegalArgumentException("Invalid date string: " + dateTime, e);
    }
    cal.set(Calendar.YEAR, year);
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
}

The method was also changed to not ignore parsing exception .该方法也被更改为不忽略解析异常


The old antiquated Date and SimpleDateFormat classes should not be used.不应使用旧的过时DateSimpleDateFormat类。 Instead, use the newer Java 8 Time API classes.相反,使用较新的Java 8 时间 API类。

protected static String paymentDatetime(String dateTime) {
    DateTimeFormatter in = new DateTimeFormatterBuilder()
            .appendPattern("ddMMHHmmss")
            .parseDefaulting(ChronoField.YEAR, Year.now().getValue())
            .toFormatter();
    DateTimeFormatter out = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    return LocalDateTime.parse(dateTime, in).format(out);
}

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

相关问题 如何将日期和时间格式从“ yyyy-MM-dd HH:mm:ss”更改为“ h:mm a”? - How to change date and time format from“yyyy-MM-dd HH:mm:ss” to “h:mm a”? 如何解析 yyyy-MM-dd HH:mm:ss 到日期? - How to parse a yyyy-MM-dd HH:mm:ss to Date? 将YYYY-MM-DD HH:MM:SS格式的java.util.Date转换为与MySQL DATETIME兼容 - Convert java.util.Date in YYYY-MM-DD HH:MM:SS format to compatible with MySQL DATETIME 以yyyy-MM-dd HH:mm:ss“格式转换日期时间 - Convert the date time in yyyy-MM-dd HH:mm:ss" format 如何将 java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) 格式化为日期(yyyy-MM-dd HH:mm:ss) - How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) 如何将 java.util.Date 转换为 soap 支持的日期格式“yyyy-MM-dd'T'HH:mm:ss”与区域 id - How to convert java.util.Date to soap suppported date format “yyyy-MM-dd'T'HH:mm:ss” with zone id 如何将 LocalDateTime 转换为`"yyyy-MM-dd'T'HH:mm:ss'Z'"` 格式 - How to convert LocalDateTime to `"yyyy-MM-dd'T'HH:mm:ss'Z'"` format 在 Java 中将日期格式“EEE MMM dd HH:mm:ss zzzz yyyy”转换为“yyyy-MM-dd'T'HH:mm:ss” - Convert date fomat “EEE MMM dd HH:mm:ss zzzz yyyy” to “yyyy-MM-dd'T'HH:mm:ss” in Java Joda DateTime格式为yyyy-MM-DD HH:MM:SS - Joda DateTime format to yyyy-MM-DD HH:MM:SS YYYY-MM-DD HH:MM:SS格式的时间值 - Time value in YYYY-MM-DD HH:MM:SS format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM