在 Java 中使用不同的格式将字符串解析为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/882420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:37:43  来源:igfitidea点击:

Parse String to Date with Different Format in Java

javastringdate

提问by Gnaniyar Zubair

I want to convert Stringto Datein different formats.

我想转换StringDate不同的格式。

For example,

例如,

I am getting from user,

我从用户那里得到,

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

I want to convert this fromDateas a Date object of "yyyy-MM-dd"format

我想将其转换fromDate"yyyy-MM-dd"格式的 Date 对象

How can I do this?

我怎样才能做到这一点?

采纳答案by Michael Myers

Take a look at SimpleDateFormat. The code goes something like this:

看看SimpleDateFormat。代码是这样的:

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();
}

回答by Matt

Check the javadocs for java.text.SimpleDateFormatIt describes everything you need.

检查 javadocsjava.text.SimpleDateFormat它描述了你需要的一切。

回答by Agora

Use the SimpleDateFormatclass:

使用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);
}

回答by James McMahon

While SimpleDateFormatwill indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

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

回答by Ritesh Kaushik

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

回答by Khalid Habib

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

回答by Basil Bourque

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 SimpleDateFormatare now outdated.

其他带有java.util.Datejava.sql.Date和 的答案SimpleDateFormat现已过时。

LocalDate

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDateclass represents a date-only value without time-of-day and without time zone.

处理日期时间的现代方法是使用 java.time 类,特别是LocalDate. 该LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

DateTimeFormatter

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatterclass.

要解析或生成表示日期时间值的字符串,请使用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. A date-time object has noformat, while a String does. A date-time object, such as LocalDate, can generatea String to represent its internal value, but the date-time object and the String are separate distinct objects.

不要将日期时间对象与表示其值的字符串混为一谈。一个日期时间对象没有格式,而字符串中。日期时间对象(例如LocalDate)可以生成字符串来表示其内部值,但日期时间对象和字符串是不同的独立对象。

You can specify any custom format to generate a 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 | output: mardi 19 mai 2009

ld: 2009-05-19 | 输出:2009 年狂欢节 19 月

See in action in IdeOne.com.

在 IdeOne.com 中查看实际操作



About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Dulith De Costa

A Dateobject has no format, it is a representation. The date can be presented by a Stringwith the format you like.

Date对象具有无格式,它是一个表示。日期可以String您喜欢格式显示

E.g. "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

回答by milad salimi

Suppose that you have a string like this :

假设你有一个这样的字符串:

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

Now we want to change this Stringformat separate date and time in Javaand Kotlin.

现在我们想StringJavaKotlin 中改变这种格式,将日期和时间分开。

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;
}

Returnis 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;
}

Returnis this :10:56 AM

Return这是:上午 10:56

KOTLIN:

科特林:

we have a function for extract date:

我们有一个提取日期的函数:

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!!)
}

Returnis 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!!)
}

Returnis this :10:56 AM

Return这是:上午 10:56