我该如何在Java中更改日期格式?

72

我需要使用Java改变日期格式,从

 dd/MM/yyyy  to yyyy/MM/dd
10个回答

159

如何使用SimpleDateFormat将日期格式从一种转换为另一种:

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);

2
请注意,旧的日期时间类(例如java.util.Datejava.util.Calendarjava.text.SimpleTextFormat)现在已经成为遗留系统,被Java.time类所取代。请参阅Oracle教程 - Basil Bourque
1
“Sdf” 对我来说听起来很奇怪,因为在法语中它的意思是“无家可归的人”。不过,还是感谢这个解决方案 :p - Y-B Cause

32
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());

这应该能解决问题


我有一个以 dd/MM/yyyy 格式表示的字符串,如何进行转换? - rasi

26

简而言之

LocalDate.parse( 
    "23/01/2017" ,  
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)

以下是翻译:

2017/01/23

避免使用旧的日期时间类

Christopher Parker的回答是正确的,但已经过时了。麻烦的旧日期时间类,如java.util.Date, java.util.Calendar, 和 java.text.SimpleTextFormat,现在已经被legacy替代,被java.time类所取代。

使用java.time

将输入字符串解析为日期时间对象,然后生成一个新的字符串对象以所需的格式。

LocalDate类表示仅包含日期值的对象,不包括时间和时区。

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK );  // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );

定义另一个用于输出的格式化程序。
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

2017/01/23

顺便提一下,考虑使用标准的ISO 8601格式来表示日期时间值的字符串。


关于java.time

java.time框架内置于Java 8及更高版本。这些类替代了老旧的legacy日期时间类,如java.util.DateCalendarSimpleDateFormat等,避免了许多麻烦。

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

要了解更多,请参见Oracle教程。并在Stack Overflow上搜索许多示例和解释。规范是JSR 310
如何获取java.time类? 这个 ThreeTen-Extra 项目是对 java.time 的扩展,提供了额外的类。该项目是 java.time 可能未来添加内容的试验场。你可以在这里找到一些有用的类,例如 IntervalYearWeekYearQuartermore

Joda-Time

更新:Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。本节内容仅供历史记录。

为了好玩,这里是使用Joda-Time库适配的代码。

// © 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.*;

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );

转储到控制台...

System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );

当运行时...

localDate: 2010-08-12
newDateString: 2010/08/12

10

使用SimpleDateFormat

    String DATE_FORMAT = "yyyy/MM/dd";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    System.out.println("Formated Date " + sdf.format(date));

完整示例:

import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaSimpleDateFormatExample {
    public static void main(String args[]) {
        // Create Date object.
        Date date = new Date();
        // Specify the desired date format
        String DATE_FORMAT = "yyyy/MM/dd";
        // Create object of SimpleDateFormat and pass the desired date format.
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        /*
         * Use format method of SimpleDateFormat class to format the date.
         */
        System.out.println("Today is " + sdf.format(date));
    }
}

我可以将字符串传递给日期吗? - rasi

4

这只是Christopher Parker的答案,经过改编以使用Java 8中的新类1

final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);

Java 9即将发布,不再是很新了。


4
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("yyyy/MM/dd")
String myDateString = sdf.format(myDate);

现在 myDateString = 2013/12/28


1
许多改变日期格式的方法。
private final String dateTimeFormatPattern = "yyyy/MM/dd";
private final Date now = new Date();  

final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);  
final String nowString = format.format(now);   

 final Instant instant = now.toInstant();  
 final DateTimeFormatter formatter =  
      DateTimeFormatter.ofPattern(  
         dateTimeFormatPattern).withZone(ZoneId.systemDefault());  
 final String formattedInstance = formatter.format(instant);  

  /* Java 8 needed*/
  LocalDate date = LocalDate.now();
  String text = date.format(formatter);
  LocalDate parsedDate = LocalDate.parse(text, formatter);

1

要更改日期格式,您需要同时使用以下两种格式。

 String stringdate1 = "28/04/2010";  

 try {

     SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
     Date date1 = format1.parse()
     SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");

     String stringdate2 = format2.format(date1);
    } catch (ParseException e) {
   e.printStackTrace();
}

这里的 stringdate2 是日期格式为 yyyy/MM/dd 的字符串,它包含了 2010/04/28

1

或者你可以选择正则表达式的方法:

String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);

它也可以双向工作。当然,这并不会实际验证您的日期,并且也适用于像“21432/32423/52352”这样的字符串。您可以使用"(\\d{2})/(\\d{2})/(\\d{4}"来更精确地指定每个组中数字的位数,但它只能从dd/MM/yyyy转换为yyyy/MM/dd,而不能反过来(并且仍然接受其中的无效数字,如45)。如果您提供了一个无效的值,例如“blabla”,它将返回相同的内容。


3
现在你有两个问题。;-) - Andrzej Doyle
感谢您对自己的方法限制如此清晰明了。 - Ole V.V.

-1
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format1.format(date));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接