【问题标题】:Change date format in a Java string更改 Java 字符串中的日期格式
【发布时间】:2021-12-16 12:57:38
【问题描述】:

我有一个 String 代表一个日期。

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

我想将其转换为Date 并以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。我做错了什么?

【问题讨论】:

  • yyyyy 与 yyyy 不同。 :)
  • 一个回旋镖问题。你的用例是什么?因为您可能应该使用内置模式 (DateFormat.getDateTimeInstance())。
  • 月份在格式字符串中用 MM 表示,而不是像上面的示例中那样用 mm 表示。 mm 表示分钟。
  • 我将 yyyy-mm-dd 更改为 yyyy-MM-dd,因为初始版本不起作用
  • "mm" 是分钟数 :)

标签: java string date formatting date-format


【解决方案1】:

答案当然是创建一个 SimpleDateFormat 对象并使用它来将字符串解析为日期并将日期格式化为字符串。如果您尝试过 SimpleDateFormat 但没有成功,请出示您的代码以及您可能收到的任何错误。

附录:字符串格式中的“mm”与“MM”不同。用 MM 表示月,用 mm 表示分钟。此外,yyyyy 与 yyyy 不同。例如:

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

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}

【讨论】:

  • 导入 java.text.ParseException;导入 java.text.SimpleDateFormat;导入 java.util.Date; public class formateDate { /** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // TODO 自动生成的方法存根 String date_s=" 2011-01-18 00:00 :00.0"; SimpleDateFormat dt= new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");日期 date=dt.parse(date_s); SimpleDateFormat dt1=new SimpleDateFormat("yyyyy-mm-dd"); System.out.println(dt1.format(date));我想输出应该是“2011-01-18”,但输出是 02011-00-1
  • 发布您拥有的任何代码作为原始问题的补充(缩进四个空格)。这样它将保留其格式,然后我们可以阅读它。
  • 请参阅上面对我的回答的编辑。您在格式字符串中使用“mm”,您应该使用“MM”
  • hh 将为您提供 1-12 范围内的小时,除了打印/解析 AMPM 之外,您还需要使用 a。要打印/解析 0-23 范围内的小时,请使用 HH
【解决方案2】:

[编辑以包括 BalusC 的更正] SimpleDateFormat 类应该可以解决问题:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

【讨论】:

  • DD 代表“一年中的一天”,而不是“一个月中的一天”。 hh 代表“上午/下午 (1-12) 中的小时”,而不是“一天中的小时 (0-23)”。
【解决方案3】:

使用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

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()Date 格式化为特定模式的String

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

另见:


更新:根据您的失败尝试:模式区分大小写。阅读java.text.SimpleDateFormat javadoc 各个部分的含义。例如,M 代表几个月,m 代表分钟。此外,存在四位数 yyyy 的年份,而不是五位数 yyyyy。仔细查看我在上面发布的代码 sn-ps。

【讨论】:

  • 如果您希望日期看起来像“2012 年 9 月 1 日星期一”怎么办?
  • @crm:只需单击 javadoc 链接,在此处找出必要的模式字符并相应地更改模式。
  • 如果您还没有使用 Java 8,请考虑使用后向端口 ThreeTen Backport,然后是答案中的第一个示例。或者对于 API 级别 26 以下的 Android,ThreeTenABP
【解决方案4】:
   String str = "2000-12-12";
   Date dt = null;
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    try 
    {
         dt = formatter.parse(str);
    }
    catch (Exception e)
    {
    }

    JOptionPane.showMessageDialog(null, formatter.format(dt));

【讨论】:

    【解决方案5】:
    private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if(value instanceof Date) {
            value = dataFormat.format(value);
        }
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    };
    

    【讨论】:

      【解决方案6】:

      从提供的格式中删除一个 y:

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

      应该是:

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

      【讨论】:

      • 不完全是。您也需要正确的案例(无论您使用现代的DateTimeFormatter 还是使用过时的SimpleDateFormat)。
      【解决方案7】:

      你也可以使用 substring()

      String date_s = "2011-01-18 00:00:00.0";
      date_s.substring(0,10);
      

      如果你想在日期前面有一个空格,请使用

      String date_s = " 2011-01-18 00:00:00.0";
      date_s.substring(1,11);
      

      【讨论】:

        【解决方案8】:

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

        时区

        还有一个问题……您没有解决时区问题。如果您打算UTC,那么您应该这么说。如果不是,则答案不完整。如果您想要的只是没有时间的日期部分,那么没问题。但是,如果您进行可能涉及时间的进一步工作,那么您应该指定一个时区。

        乔达时间

        这里是同一种代码,但是使用了第三方开源的Joda-Time2.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
        

        【讨论】:

          【解决方案9】:
          try
           {
              String date_s = "2011-01-18 00:00:00.0";
              SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
              Date tempDate=simpledateformat.parse(date_s);
              SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");           
              System.out.println("Output date is = "+outputDateFormat.format(tempDate));
            } catch (ParseException ex) 
            {
                  System.out.println("Parse Exception");
            }
          

          【讨论】:

            【解决方案10】:

            在 Java 8 及更高版本中使用 java.time 包:

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

            【讨论】:

              【解决方案11】:

              为什么不简单地使用这个

              Date convertToDate(String receivedDate) throws ParseException{
                      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                      Date date = formatter.parse(receivedDate);
                      return date;
                  }
              

              另外,这是另一种方式:

              DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
              String requiredDate = df.format(new Date()).toString();
              

              Date requiredDate = df.format(new Date());
              

              【讨论】:

              • 为什么不用这个?因为(a)它忽略了时区的问题。确定日期取决于时区。此代码取决于 JVM 的默认时区。因此,结果可能会在不经意间发生变化。并且 (b) 因为 java.util.Date 和 SimpleDateFormat 类是出了名的麻烦,应该避免使用。
              • 总是返回字符串,Date requiredDate = df.format(new Date());
              【解决方案12】:

              你可以使用:

              Date yourDate = new Date();
              
              SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
              String date = DATE_FORMAT.format(yourDate);
              

              效果很好!

              【讨论】:

              • 此代码返回错误“Uncaught SyntaxError: Unexpected identifier”
              • @IvanFrolov 可能是您缺少导入,您在哪一行收到错误?
              • 哦,抱歉 - 没有注意到它是 Java 的解决方案,我已经搜索了 javascript 的解决方案)))(顺便说一句 - 已经找到)。谢谢!
              • 啊好吧,现在很明显了。
              【解决方案13】:

              格式区分大小写,因此使用 MM 表示月份而不是 mm(这是分钟)和 yyyy 对于Reference,您可以使用以下备忘单。

              G   Era designator  Text    AD
              y   Year    Year    1996; 96
              Y   Week year   Year    2009; 09
              M   Month in year   Month   July; Jul; 07
              w   Week in year    Number  27
              W   Week in month   Number  2
              D   Day in year Number  189
              d   Day in month    Number  10
              F   Day of week in month    Number  2
              E   Day name in week    Text    Tuesday; Tue
              u   Day number of week (1 = Monday, ..., 7 = Sunday)    Number  1
              a   Am/pm marker    Text    PM
              H   Hour in day (0-23)  Number  0
              k   Hour in day (1-24)  Number  24
              K   Hour in am/pm (0-11)    Number  0
              h   Hour in am/pm (1-12)    Number  12
              m   Minute in hour  Number  30
              s   Second in minute    Number  55
              S   Millisecond Number  978
              z   Time zone   General time zone   Pacific Standard Time; PST; GMT-08:00
              Z   Time zone   RFC 822 time zone   -0800
              X   Time zone   ISO 8601 time zone  -08; -0800; -08:00
              

              例子:

              "yyyy.MM.dd G 'at' HH:mm:ss z"  2001.07.04 AD at 12:08:56 PDT
              "EEE, MMM d, ''yy"  Wed, Jul 4, '01
              "h:mm a"    12:08 PM
              "hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
              "K:mm a, z" 0:08 PM, PDT
              "yyyyy.MMMMM.dd GGG hh:mm aaa"  02001.July.04 AD 12:08 PM
              "EEE, d MMM yyyy HH:mm:ss Z"    Wed, 4 Jul 2001 12:08:56 -0700
              "yyMMddHHmmssZ" 010704120856-0700
              "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"   2001-07-04T12:08:56.235-0700
              "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"   2001-07-04T12:08:56.235-07:00
              "YYYY-'W'ww-u"  2001-W27-3
              

              【讨论】:

              • "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 应该是 "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
              • 不,如果你把 Z 放在单引号中,它会给出 Z 作为输出,但没有它会给出时区。例如。 2014-08-14T01:24:57.236Z 和没有它 2014-08-14T01:24:57.236-0530 --> 我试过 jdk1.7
              • "yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM 注意月份中的额外 M。四个不是五个!
              • 如果是 4 个字母或更多,则使用完整的形式。所以你可以使用 4 倍 m 甚至 5 倍 m 相同
              • 这几乎是文档的复制粘贴。没有提供额外的解释,也没有指向文档的链接,如果需要可以获取更多信息。 -1。 (Here's the link btw)
              【解决方案14】:

              您可以尝试 Java 8 新的date,更多信息可以在Oracle documentation 上找到。

              或者你可以试试旧的

              public static Date getDateFromString(String format, String dateStr) {
              
                  DateFormat formatter = new SimpleDateFormat(format);
                  Date date = null;
                  try {
                      date = (Date) formatter.parse(dateStr);
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
              
                  return date;
              }
              
              public static String getDate(Date date, String dateFormat) {
                  DateFormat formatter = new SimpleDateFormat(dateFormat);
                  return formatter.format(date);
              }
              

              【讨论】:

                【解决方案15】:

                请参阅此处的“日期和时间模式”。 http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

                import java.text.SimpleDateFormat;
                import java.util.Date;
                import java.text.ParseException;
                
                public class DateConversionExample{
                
                  public static void main(String arg[]){
                
                    try{
                
                    SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
                
                    Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");
                
                
                    SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    System.out.println(targetDateFormat.format(date));
                
                    }catch(ParseException e){
                        e.printStackTrace();
                    }
                  } 
                
                }
                

                【讨论】:

                  【解决方案16】:
                  public class SystemDateTest {
                  
                      String stringDate;
                  
                      public static void main(String[] args) {
                          SystemDateTest systemDateTest = new SystemDateTest();
                          // format date into String
                          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
                          systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
                          System.out.println(systemDateTest.getStringDate());
                      }
                  
                      public Date getDate() {
                          return new Date();
                      }
                  
                      public String getStringDate() {
                          return stringDate;
                      }
                  
                      public void setStringDate(String stringDate) {
                          this.stringDate = stringDate;
                      }
                  }
                  

                  【讨论】:

                  • 请在您的答案中添加一些信息来解释您的代码。
                  • 有一个方法名称 getDate() ,您可以通过它在应用 SimpleDateFormat 之后获取日期 obj ,以便您可以根据您在 SimpleDateFormat 构造函数中定义并在 StringDate 方法中设置的格式转换日期使其缓存
                  【解决方案17】:
                  SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
                  

                  【讨论】:

                  • 这个日期时间类在几年前被现代的 java.time 类所取代。特别是DateTimeFormatterDateTimeFormatterBuilder。在 2019 年建议 SimpleDateFormat 是糟糕的建议。
                  • 不正确您在此处的格式代码错误。 hh 是一小时。
                  • 通常我们期待一些讨论或解释。 Stack Overflow 不仅仅是一个 sn-p 库。
                  【解决方案18】:

                  假设您想将 2019-12-20 10:50 AM GMT+6:00 更改为 2019-12-20 10:50 AM 首先你必须了解日期格式第一个日期格式是 yyyy-MM-dd hh:mm a zzz 和第二个日期格式将为 yyyy-MM-dd hh:mm a

                  只是从这个函数返回一个字符串,比如。

                  public String convertToOnlyDate(String currentDate) {
                      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a ");
                      Date date;
                      String dateString = "";
                      try {
                          date = dateFormat.parse(currentDate);
                          System.out.println(date.toString()); 
                  
                          dateString = dateFormat.format(date);
                      } catch (ParseException e) {
                          e.printStackTrace();
                      }
                      return dateString;
                  }
                  

                  此函数将返回您想要的答案。如果您想自定义更多,只需从日期格式中添加或删除组件。

                  【讨论】:

                    【解决方案19】:

                    我们可以将今天的日期转换为'JUN 12, 2020'的格式

                    String.valueOf(DateFormat.getDateInstance().format(new Date())));
                    

                    【讨论】:

                      【解决方案20】:

                      你有一些错误: SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

                      首先: 应该 new SimpleDateFormat("yyyy-mm-dd"); //yyyy 4 不是 5 这个显示 02011,但它显示的是 2011

                      秒: 像这样更改您的代码 new SimpleDateFormat("yyyy-MM-dd");

                      希望对你有帮助

                      【讨论】:

                        【解决方案21】:
                        /**
                         * Method will take Date in "MMMM, dd yyyy HH:mm:s" format and return time difference like added: 3 min ago
                         *
                         * @param date : date in "MMMM, dd yyyy HH:mm:s" format
                         * @return : time difference
                         */
                        private String getDurationTimeStamp(String date) {
                            String timeDifference = "";
                        
                            //date formatter as per the coder need
                            SimpleDateFormat sdf = new SimpleDateFormat("MMMM, dd yyyy HH:mm:s");
                            TimeZone timeZone = TimeZone.getTimeZone("EST");
                            sdf.setTimeZone(timeZone);
                            Date startDate = null;
                            try {
                                startDate = sdf.parse(date);
                            } catch (ParseException e) {
                                MyLog.printStack(e);
                            }
                        
                            //end date will be the current system time to calculate the lapse time difference
                            Date endDate = new Date();
                        
                            //get the time difference in milliseconds
                            long duration = endDate.getTime() - startDate.getTime();
                        
                            long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
                            long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
                            long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
                            long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
                        
                            if (diffInDays >= 365) {
                                int year = (int) (diffInDays / 365);
                                timeDifference = year + mContext.getString(R.string.year_ago);
                            } else if (diffInDays >= 30) {
                                int month = (int) (diffInDays / 30);
                                timeDifference = month + mContext.getString(R.string.month_ago);
                            }
                            //if days are not enough to create year then get the days
                            else if (diffInDays >= 1) {
                                timeDifference = diffInDays + mContext.getString(R.string.day_ago);
                            }
                            //if days value<1 then get the hours
                            else if (diffInHours >= 1) {
                                timeDifference = diffInHours + mContext.getString(R.string.hour_ago);
                            }
                            //if hours value<1 then get the minutes
                            else if (diffInMinutes >= 1) {
                                timeDifference = diffInMinutes + mContext.getString(R.string.min_ago);
                            }
                            //if minutes value<1 then get the seconds
                            else if (diffInSeconds >= 1) {
                                timeDifference = diffInSeconds + mContext.getString(R.string.sec_ago);
                            } else if (timeDifference.isEmpty()) {
                                timeDifference = mContext.getString(R.string.now);
                            }
                        
                            return mContext.getString(R.string.added) + " " + timeDifference;
                        }
                        

                        【讨论】:

                          【解决方案22】:

                          java.time

                          java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

                          另外,下面引用的是来自home page of Joda-Time的通知:

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

                          使用现代日期时间 API java.time 的解决方案:

                          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, the old way:
                                  // LocalDateTime ldt = dtfInput.parse(strDate, LocalDateTime::from);
                          
                                  LocalDate date = ldt.toLocalDate();
                                  System.out.println(date);
                              }
                          }
                          

                          输出:

                          2011-01-18
                          

                          ONLINE DEMO

                          关于解决方案的一些重要说明:

                          1. java.time 使得在Date-Time type 本身上调用parseformat 函数成为可能,除了旧的方式(即在格式化程序类型上调用parseformat 函数,即DateTimeFormatterjava.time API 的情况下)。
                          2. 现代日期时间 API 基于ISO 8601,只要日期时间字符串符合 ISO 8601 标准,就不需要显式使用DateTimeFormatter 对象。我没有使用DateTimeFormatter 作为输出,因为LocalDate#toString 已经返回了所需格式的字符串。
                          3. 在这里,您可以使用y 代替u,但可以使用I prefer u to y

                          Trail: Date Time 了解有关现代日期时间 API 的更多信息。


                          * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

                          【讨论】:

                            猜你喜欢
                            • 2023-03-18
                            • 2016-06-25
                            • 1970-01-01
                            • 2011-05-04
                            • 2022-07-04
                            • 1970-01-01
                            • 2021-05-07
                            相关资源
                            最近更新 更多