简体   繁体   English

在 Java 中解析不同格式的字符串到日期

[英]Parse String to Date with Different Format in Java

I want to convert String to Date in different formats.我想将String转换为不同格式的Date

For example,例如,

I am getting from user,我从用户那里得到,

String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format

I want to convert this fromDate as a Date object of "yyyy-MM-dd" format我想将此fromDate转换为"yyyy-MM-dd"格式的日期 object

How can I do this?我怎样才能做到这一点?

Take a look at SimpleDateFormat . 看看SimpleDateFormat The code goes something like this: 代码如下:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

Use the SimpleDateFormat class: 使用SimpleDateFormat类:

private Date parseDate(String date, String format) throws ParseException
{
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.parse(date);
}

Usage: 用法:

Date date = parseDate("19/05/2009", "dd/MM/yyyy");

For efficiency, you would want to store your formatters in a hashmap. 为了提高效率,您需要将格式化程序存储在散列映射中。 The hashmap is a static member of your util class. hashmap是util类的静态成员。

private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();

public static Date parseDate(String date, String format) throws ParseException
{
    SimpleDateFormat formatter = hashFormatters.get(format);

    if (formatter == null)
    {
        formatter = new SimpleDateFormat(format);
        hashFormatters.put(format, formatter);
    }

    return formatter.parse(date);
}

tl;dr TL;博士

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

Details 细节

The other Answers with java.util.Date , java.sql.Date , and SimpleDateFormat are now outdated. java.util.Datejava.sql.DateSimpleDateFormat的其他Answers现在已经过时了。

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate . 执行日期时间的现代方法是使用java.time类,特别是LocalDate The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有时间且没有时区的仅日期值。

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class. 要解析或生成表示日期时间值的String,请使用DateTimeFormatter类。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

Do not conflate a date-time object with a String representing its value. 不要将日期时间对象与表示其值的String混淆。 A date-time object has no format , while a String does. 日期时间对象没有格式 ,而String则没有格式 A date-time object, such as LocalDate , can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects. 日期时间对象(如LocalDate )可以生成表示其内部值的String,但日期时间对象和String是不同的不同对象。

You can specify any custom format to generate a String. 您可以指定任何自定义格式以生成String。 Or let java.time do the work of automatically localizing. 或者让java.time完成自动本地化的工作。

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

Dump to console. 转储到控制台。

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 | ld:2009-05-19 | output: mardi 19 mai 2009 输出:mardi 19 mai 2009

See in action in IdeOne.com . 请参阅IdeOne.com中的操作


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 ,和更多

Convert a string date to java.sql.Date 将字符串日期转换为java.sql.Date

String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010

检查javadocs以获取java.text.SimpleDateFormat它描述了您需要的一切。

虽然SimpleDateFormat确实可以满足您的需求,但您可能还想查看Joda Time ,这显然是Java 7中重做日期库的基础。虽然我没有经常使用它,但我听到的只是好的关于它的事情,如果你的操纵日期在你的项目中广泛,它可能值得研究。

Suppose that you have a string like this:假设你有这样一个字符串:

String mDate="2019-09-17T10:56:07.827088"

Now we want to change this String format separate date and time in Java and Kotlin .现在我们想在JavaKotlin中将此String格式更改为单独的日期和时间。

JAVA: JAVA:

we have a method for extract date :我们有一个提取日期的方法:

public String getDate() {
    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        Date date = dateFormat.parse(mDate);
        dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
        return dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

Return is this: 09/17/2019 Return是这里:09/17/2019

And we have method for extract time :我们有提取时间的方法:

public String getTime() {

    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        Date date = dateFormat.parse(mCreatedAt);
        dateFormat = new SimpleDateFormat("h:mm a", Locale.US);
        return dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

Return is this: 10:56 AM Return是:上午10点56分

KOTLIN: KOTLIN:

we have a function for extract date :我们有一个 function 作为提取日期

fun getDate(): String? {

    var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
    val date = dateFormat.parse(mDate!!)
    dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
    return dateFormat.format(date!!)
}

Return is this: 09/17/2019 Return是这里:09/17/2019

And we have method for extract time :我们有提取时间的方法:

fun getTime(): String {

    var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
    val time = dateFormat.parse(mDate!!)
    dateFormat = SimpleDateFormat("h:mm a", Locale.US)
    return dateFormat.format(time!!)
}

Return is this: 10:56 AM Return是:上午10点56分

Simple way to format a date and convert into string 格式化日期并转换为字符串的简单方法

    Date date= new Date();

    String dateStr=String.format("%td/%tm/%tY", date,date,date);

    System.out.println("Date with format of dd/mm/dd: "+dateStr);

output:Date with format of dd/mm/dd: 21/10/2015 输出:日期格式为dd / mm / dd:21/10/2015

A Date object has no format , it is a representation. Date对象没有格式 ,它是一种表示。 The date can be presented by a String with the format you like . 日期可以用您喜欢格式String

Eg " yyyy-MM-dd ", " yy-MMM-dd ", " dd-MMM-yy " and etc. 例如“ yyyy-MM-dd ”,“ yy-MMM-dd ”,“ dd-MMM-yy ”等。

To acheive this you can get the use of the SimpleDateFormat 为了实现这一目标,您可以使用SimpleDateFormat

Try this, 试试这个,

        String inputString = "19/05/2009"; // i.e. (dd/MM/yyyy) format

        SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); 
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date dateFromUser = fromUser.parse(inputString); // Parse it to the exisitng date pattern and return Date type
            String dateMyFormat = myFormat.format(dateFromUser); // format it to the date pattern you prefer
            System.out.println(dateMyFormat); // outputs : 2009-05-19

        } catch (ParseException e) {
            e.printStackTrace();
        }

This outputs : 2009-05-19 输出结果:2009-05-19

There are multiple ways to do it, but a very practical one is the use String.format which you can use with java.util.Date or java.util.Calendar or event java.time.LocalDate .有多种方法可以做到这一点,但一个非常实用的方法是使用String.format ,您可以将其与java.util.Datejava.util.Calendar或事件java.time.LocalDate使用。

String.format is backed by java.util.Formatter . String.formatjava.util.Formatter支持。

I like the omnivore take on it.我喜欢杂食动物。

class Playground {
    public static void main(String[ ] args) {
        String formatString = "Created on %1$td/%1$tm/%1$tY%n";
        System.out.println(String.format(formatString, new java.util.Date()));
        System.out.println(String.format(formatString, java.util.Calendar.getInstance()));
        System.out.println(String.format(formatString, java.time.LocalDate.now()));
    }
}

The output will be in all cases: output 在所有情况下都是:

Created on 04/12/2022

Created on 04/12/2022

Created on 04/12/2022

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

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