我有一个表示日期的字符串。

String date_s = "2011-01-18 00:00:00.0";

我想把它转换成一个日期,并以YYYY-MM-DD格式输出。

2011-01-18

我怎样才能做到这一点呢?


好吧,根据我在下面找到的答案,以下是我尝试过的一些方法:

String date_s = " 2011-01-18 00:00:00.0"; 
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); 
Date date = dt.parse(date_s); 
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

但是它输出02011-00-1而不是所需的2011-01-18。我做错了什么?


当前回答

使用LocalDateTime#parse()(如果字符串碰巧包含时区部分,则使用ZonedDateTime#parse())将某个模式下的string解析为LocalDateTime。

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

然后使用localdatetime# format()(或zoneddatetime# format())将LocalDateTime格式化为特定模式的字符串。

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

或者,如果您还没有使用Java 8,可以使用SimpleDateFormat#parse()将特定模式下的String解析为Date。

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

然后使用SimpleDateFormat#format()将日期格式化为特定模式的字符串。

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

参见:

Java字符串到日期的转换


更新:根据你的失败的尝试,你添加到这个问题后的答案张贴;模式是区分大小写的。仔细阅读java.text.SimpleDateFormat javadoc中各个部分代表什么。举个例子,M代表月,M代表分钟。此外,年份是四位数yyyy,而不是五位数yyyyy。仔细看看我上面发布的代码片段。

其他回答

你错了: SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

第一: 应该是 新SimpleDateFormat(“yyyy-mm-dd”); //yyyy 4而不是5 这个显示02011,但是yyyy显示2011

第二: 像这样更改代码 新SimpleDateFormat(“yyyy-MM-dd”);

希望能帮到你

从格式中删除一个y:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

它应该是:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

java.time

2014年3月,现代日期时间API* API取代了容易出错的java。SimpleDateFormat. util日期时间API和它们的格式化API。从那时起,强烈建议停止使用遗留API。

此外,下面引用的是Joda-Time主页的通知:

注意,从Java SE 8开始,用户被要求迁移到Java。time (JSR-310)——JDK的核心部分,取代了这个项目。

格式化不需要DateTimeFormatter

您只需要DateTimeFormatter来解析字符串,但不需要DateTimeFormatter来获得所需格式的日期。现代Date-Time API基于ISO 8601,因此是java的toString实现。时间类型返回ISO 8601格式的字符串。您想要的格式是localdate# toString的默认格式。

使用java解决方案。time,现代Date-Time API:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDate = "2011-01-18 00:00:00.0";
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(strDate, dtfInput);
        // Alternatively,
        // LocalDateTime ldt = dtfInput.parse(strDate, LocalDateTime::from);

        LocalDate date = ldt.toLocalDate();
        System.out.println(date);
    }
}

输出:

2011-01-18

在线演示

关于解决方案的一些重要注意事项:

java。time使得在Date-Time类型本身上调用解析和格式化函数成为可能,除了传统的方式(即在formatter类型上调用解析和格式化函数,在java中是DateTimeFormatter。时间API)。 这里,你可以用y代替u但我更喜欢u而不是y。

从Trail: Date Time了解更多关于现代Date-Time API的信息。


*无论出于何种原因,如果你必须坚持使用Java 6或Java 7,你可以使用ThreeTen-Backport,它可以向后移植大部分Java。Java 6和7的时间功能。如果你正在为一个Android项目工作,你的Android API级别仍然不兼容Java-8,检查Java 8+ API通过desugaring和如何使用ThreeTenABP在Android项目。

其他答案是正确的,基本上你在你的图案中有错误数量的“y”字符。

时区

还有一个问题,你没有提到时区。如果你指的是UTC,那么你应该这么说。如果不是,说明答案不完整。如果您只需要日期部分而不需要时间,那么没有问题。但是如果您要做的进一步工作可能涉及到时间,那么您应该指定一个时区。

乔达时间

下面是相同类型的代码,但是使用了第三方开源的Joda-Time 2.3库

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String date_s = "2011-01-18 00:00:00.0";

org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );

// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.

// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );

运行时……

dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18

dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z

使用java。Java 8及以上版本的时间包:

String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
    .ofPattern("yyyy-MM-dd HH:mm:ss.S")
    .parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);