如何将日期转换为 yyyy-MM-dd 格式?

问题描述 投票:0回答:6

2012 年 12 月 1 日星期六 00:00:00 GMT

我必须将上面的日期转换为下面的格式

2012-12-01

我能怎样?

我尝试过以下方法,但不起作用

public Date ConvertDate(Date date){

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String s = df.format(date);
    String result = s;
    try {
        date=df.parse(result);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
  }
java date simpledateformat date-formatting
6个回答
94
投票

用这个。

java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);

您将得到如下输出

2012-12-01

4
投票
String s;
Format formatter;
Date date = new Date();

// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);

4
投票

更新我的答案现在已经过时了。 Joda-Time 项目现在处于维护模式,建议迁移到 java.time 类。请参阅 Ole V.V. 的回答 中的现代解决方案。

乔达时间

NidhishKrishnan接受的答案是正确的。

为了好玩,这里有 Joda-Time 2.3 中的相同类型的代码。

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

java.util.Date date = new Date(); // A Date object coming from other code.

// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );

运行时...

dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30

4
投票

现代答案:使用

LocalDate
中的
java.time
,现代 Java 日期和时间 API 及其
toString
方法:

    LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
    String formattedDate = date.toString();
    System.out.println(formattedDate);

此打印

2012-12-01

有些人会更喜欢更明确的:

    String formattedDate = date.format(DateTimeFormatter.ISO_LOCAL_DATE);

格式化程序名称中的 ISO 指的是 ISO 8601 标准。根据它,日期的格式设置为您想要的方式,如

yyyy-mm-dd

日期(无论我们是在谈论

java.util.Date
还是
java.time.LocalDate
)没有格式。它所拥有的只是一个产生某种格式的
toString
方法,并且您无法更改
toString
方法。幸运的是,
LocalDate.toString
生成的格式正是您所要求的。

Date
类早已过时,而您尝试使用的
SimpleDateFormat
类非常麻烦。我建议您忘记这些课程并使用
java.time
代替。现代 API 更易于使用。

例外:您碰巧从旧版 API 中获得了

Date
,而您现在无法更改或不想更改。您可以用它做的最好的事情是将其转换为
java.time.Instant
并从那里进行任何进一步的操作:

    Date oldfashoinedDate = // get from somewhere
    LocalDate date = oldfashoinedDate.toInstant()
            .atZone(ZoneId.of("Asia/Beirut"))
            .toLocalDate();

如果不是亚洲/贝鲁特,请替换您所需的时区。然后按照上面的方法进行。

链接: Oracle教程:日期时间,解释如何使用

java.time


2
投票

您无法格式化

Date
本身。您只能在
String
中获得格式化结果。正如其他人提到的那样,使用
SimpleDateFormat

而且,大部分

getter methods in Date
都是
deprecated.


1
投票

日期时间对象应该存储有关日期、时间、时区等的信息,而不是关于格式。您可以使用日期时间格式化 API 将日期时间对象格式化为具有您选择的模式的

String

  • 现代日期时间类型的日期时间格式化 API 位于包中,
    java.time.format
    ,例如
    java.time.format.DateTimeFormatter
    java.time.format.DateTimeFormatterBuilder
  • 旧日期时间类型的日期时间格式化 API 位于包中,
    java.text
    ,例如
    java.text.SimpleDateFormat
    java.text.DateFormat

使用现代 API 的演示:

import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
                ZoneId.of("Europe/London"));

        // Default format returned by Date#toString
        System.out.println(zdt);

        // Custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
        String formattedDate = dtf.format(zdt);
        System.out.println(formattedDate);
    }
}

输出:

2012-12-01T00:00Z[Europe/London]
2012-12-01

Trail:日期时间了解现代日期时间 API。

使用旧版 API 的演示:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        calendar.setTimeInMillis(0);
        calendar.set(Calendar.YEAR, 2012);
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date date = calendar.getTime();

        // Default format returned by Date#toString
        System.out.println(date);

        // Custom format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        String formattedDate = sdf.format(date);
        System.out.println(formattedDate);
    }
}

输出:

Sat Dec 01 00:00:00 GMT 2012
2012-12-01

一些更重要的点:

  1. java.util.Date
    对象不是像现代日期时间类型那样的真正的日期时间对象;相反,它代表从
    Epoch of January 1, 1970
    算起的毫秒数。当您打印
    java.util.Date
    的对象时,其
    toString
    方法返回根据该毫秒值计算的日期时间。由于
    java.util.Date
    没有时区信息,因此它会应用 JVM 的时区并显示相同的信息。如果您需要打印不同时区的日期时间,则需要将时区设置为
    SimpleDateFomrat
    并从中获取格式化字符串。
  2. java.util
    的日期时间 API 及其格式化 API
    SimpleDateFormat
    已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API
© www.soinside.com 2019 - 2024. All rights reserved.