简体   繁体   English

从任何格式以 yyyy-MM-dd hh:mm:ss 格式格式化日期

[英]Format date in yyyy-MM-dd hh:mm:ss format from whatever format

I am having various date String and want to format in particular format using java我有各种日期字符串,并想使用 java 以特定格式格式化

String arr[] = {"Jul 02,2020 ","15-10-2015 10:20:56","2015/10/26 12:10:39","27-04-2016 10:22:56","April 7, 2020"};
    Arrays.asList(arr).forEach(date->{
        try {
            System.out.println(convertDate(date, "yyyy-MM-dd hh:mm:ss"));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });

public static String getDateString(String date,String patternStr) throws ParseException {
    if(StringUtils.isNotEmpty(date)&& StringUtils.isNotEmpty(patternStr)) {
        SimpleDateFormat pattern = new SimpleDateFormat(patternStr);
        Date dateObject =new Date(date);
        return pattern.format(dateObject).toString();
    }
    return date;
}

But i am getting parse Exception for some of the date value.Is there any generic way to support for all the input date value .但是我正在解析某些日期值的异常。是否有任何通用方法来支持所有input date value

I recommend you switch from the outdated and error-prone java.util date-time API to the rich set of modern date-time API .我建议您从过时且容易出错的java.util日期时间 API 切换到丰富的现代日期时间 API 集 Using DateTimeFormatterBuilder , you can build a format including all expected date-time formats and hour, minute, second defaulting to 0 .使用DateTimeFormatterBuilder ,您可以构建一个格式,包括所有预期的日期时间格式和默认为0的小时、分钟、秒。

Demo演示

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

public class Main {
    public static void main(final String[] args) {
        String arr[] = { "Jul 02,2020 ", "15-10-2015 10:20:56", "2015/10/26 12:10:39", "27-04-2016 10:22:56",
                "April 7, 2020" };
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .appendPattern("[MMM d,yyyy]")
                                        .appendPattern("[dd-MM-yyyy HH:mm:ss]")
                                        .appendPattern("[yyyy/MM/dd HH:mm:ss]")
                                        .appendPattern("[dd-MM-yyyy HH:mm:ss]")
                                        .appendPattern("[MMMM d, yyyy]")
                                        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                                        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                        .toFormatter();

        for (String s : arr) {
            LocalDateTime ldt = LocalDateTime.parse(s.trim(), formatter);
            System.out.println("LocalDate#toString: " + ldt + ", " + "Formatted: "
                    + ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
    }
}

Output: Output:

LocalDate#toString: 2020-07-02T00:00, Formatted: 2020-07-02 00:00:00
LocalDate#toString: 2015-10-15T10:20:56, Formatted: 2015-10-15 10:20:56
LocalDate#toString: 2015-10-26T12:10:39, Formatted: 2015-10-26 12:10:39
LocalDate#toString: 2016-04-27T10:22:56, Formatted: 2016-04-27 10:22:56
LocalDate#toString: 2020-04-07T00:00, Formatted: 2020-04-07 00:00:00

No way you can do that.你不可能那样做。 For every Date string, you need to pass the pattern along with it.对于每个日期字符串,您需要将模式连同它一起传递。 Else you have to build your own String parser which can be ugly and cumbersome.否则,您必须构建自己的字符串解析器,这可能既丑陋又麻烦。

First of all the constructor accepting String is deprecated as of JDK version 1.1, replaced by DateFormat.parse(String s).首先,接受 String 的构造函数从 JDK 版本 1.1 开始被弃用,由 DateFormat.parse(String s) 取代。

Check the doc检查 文档

The right way to parse date from string is:从字符串中解析日期的正确方法是:

String sDate1="31/12/1998";  
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);

暂无
暂无

声明:本站的技术帖子网页,遵循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”? 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 日期从yyyy-MM-dd HH:mm:ss转换为ISO日期yyyy-MM-dd'T'HH:mm:ssXXX格式问题 - Date conversion from yyyy-MM-dd HH:mm:ss to ISO date yyyy-MM-dd'T'HH:mm:ssXXX format issue 如何以yyyy-MM-dd HH:mm:ss格式从Oracle数据库检索Date变量并以相同格式存储在Date变量中? - How to retrieve the Date variable from oracle database in yyyy-MM-dd HH:mm:ss format and store in Date variable in the same format? Java 格式 yyyy-MM-dd'T'HH:mm:ss.SSSz 到 yyyy-mm-dd HH:mm:ss - Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss 如何将 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 7中将字符串日期转换为yyyy-MM-dd'T'HH:mm:ss.SSSSSS格式的字符串 - Converting string date to string in yyyy-MM-dd'T'HH:mm:ss.SSSSSS format in java 7 Oracle日期格式更改为yyyy-MM-dd hh:mm:ss - Oracle Date Format change to yyyy-MM-dd hh:mm:ss YYYY-MM-DD HH:MM:SS[.fraction] 格式的 MySQL 更新日期字段 - MySQL update date field in YYYY-MM-DD HH:MM:SS[.fraction] format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM