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

时间:2009-05-19 12:22:40

标签: java string date

我想以不同格式将String转换为Date

例如,

我来自用户,

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

我想将此fromDate转换为"yyyy-MM-dd"格式

的Date对象

我该怎么做?

9 个答案:

答案 0 :(得分:172)

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

答案 1 :(得分:12)

使用SimpleDateFormat类:

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

用法:

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

为了提高效率,您需要将格式化程序存储在散列映射中。 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);
}

答案 2 :(得分:9)

TL;博士

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

详细

java.util.Datejava.sql.DateSimpleDateFormat的其他答案现已过时。

LocalDate

现代的日期时间方法是使用java.time类,特别是LocalDateLocalDate类表示没有时间且没有时区的仅限日期的值。

DateTimeFormatter

要解析或生成表示日期时间值的String,请使用DateTimeFormatter类。

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

不要将日期时间对象与表示其值的String混淆。日期时间对象具有格式,而String则具有。日期时间对象(例如LocalDate)可以生成字符串以表示其内部值,但日期时间对象和字符串是不同的独立对象。

您可以指定任何自定义格式来生成String。或者让java.time完成自动本地化的工作。

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

转储到控制台。

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

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

See in action in IdeOne.com

关于 java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和&amp; SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

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

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 3 :(得分:7)

将字符串日期转换为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

答案 4 :(得分:5)

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

答案 5 :(得分:3)

虽然SimpleDateFormat确实可以满足您的需求,但您可能还需要查看Joda Time,这显然是Java 7中重做日期库的基础。虽然我没有使用它很多,我没有听到任何关于它的好消息,如果你的项目在你的项目中广泛使用,那么它可能值得研究。

答案 6 :(得分:1)

格式化日期并转换为字符串的简单方法

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

输出:日期格式为dd / mm / dd:21/10/2015

答案 7 :(得分:1)

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

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

现在,我们要在 Java Kotlin 中分别更改此String格式的日期和时间。

JAVA:

我们有一种提取日期的方法:

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是这样的:09/17/2019

我们有提取时间的方法:

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是这个: 上午10:56

科特琳:

我们具有提取日期的功能:

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是这样的:09/17/2019

我们有提取时间的方法:

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是这个: 上午10:56

答案 8 :(得分:0)

A Date object has no format, it is a representation. The date can be presented by a String with the format you like.

E.g. "yyyy-MM-dd", "yy-MMM-dd", "dd-MMM-yy" and etc.

To acheive this you can get the use of the 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

相关问题