如何更改 Java 中的日期格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3469507/
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-14 01:03:56  来源:igfitidea点击:

How can I change the date format in Java?

javadate

提问by rasi

I need to change the date format using Java from

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

 dd/MM/yyyy  to yyyy/MM/dd

采纳答案by Christopher Parker

How to convert from one date format to another using SimpleDateFormat:

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

回答by YoK

Use SimpleDateFormat

使用SimpleDateFormat

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

Complete Example:

完整示例:

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

回答by KristofMols

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

This should do the trick

这应该可以解决问题

回答by Andrei Fierbinteanu

Or you could go the regex route:

或者你可以走正则表达式路线:

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

It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}"to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.

它也适用于两种方式。当然,这实际上不会验证您的日期,也适用于“21432/32423/52352”之类的字符串。您可以使用"(\\d{2})/(\\d{2})/(\\d{4}"更精确的每个组中的位数,但它只能从 dd/MM/yyyy 到 yyyy/MM/dd 工作,而不再反过来(并且仍然接受无效数字,例如 45 )。如果你给它一些无效的东西,比如“blabla”,它只会返回同样的东西。

回答by Nikolay Hristov

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

Now MyDate = 2013/12/28

现在我的日期 = 2013/12/28

回答by Basil Bourque

tl;dr

tl;博士

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

2017/01/23

2017/01/23

Avoid legacy date-time classes

避免遗留的日期时间类

The answer by Christopher Parkeris correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormatare now legacy, supplanted by the java.timeclasses.

Christopher Parker答案是正确的,但已经过时了。麻烦的旧日期,时间类,如java.util.Datejava.util.Calendarjava.text.SimpleTextFormat现在的遗产,由取代java.time类。

Using java.time

使用 java.time

Parse the input string as a date-time object, then generate a new String object in the desired format.

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

The LocalDateclass represents a date-only value without time-of-day and without time zone.

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

Define another formatter for the output.

为输出定义另一个格式化程序。

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

2017/01/23

2017/01/23

By the way, consider using standard ISO 8601formats for strings representing date-time values.

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



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

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,和更多



Joda-Time

乔达时间

UPDATE:The Joda-Timeproject is now in maintenance mode, with the team advising migration to the java.timeclasses. This section here is left for the sake of history.

UPDATE:乔达时间的项目现在处于维护模式,与团队的建议迁移java.time类。这部分是为了历史而留下的。

For fun, here is his code adapted for using the Joda-Timelibrary.

为了好玩,这里是他为使用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 );

Dump to console…

转储到控制台...

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

When run…

运行时…

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

回答by Sneha Phalke

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

回答by Divyesh Kanzariya

many ways to change date format

更改日期格式的多种方法

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

回答by Divyesh Kanzariya

To Change the format of Date you have Require both format look below.

要更改您拥有的日期格式,请查看下面的两种格式。

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

here stringdate2have date format of yyyy/MM/dd. and it contain 2010/04/28.

这里的stringdate2日期格式为yyyy/MM/dd. 它包含2010/04/28.

回答by user85421

This is just Christopher Parker's answeradapted to use the new1classes from Java 8:

这只是克里斯托弗·帕克 (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);

1 well, not that new anymore, Java 9 should be released soon.

1 好吧,不再那么新了,Java 9 应该很快就会发布。