【问题标题】:How to convert date in to yyyy-MM-dd Format?如何将日期转换为 yyyy-MM-dd 格式?
【发布时间】:2012-12-11 22:07:04
【问题描述】:

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

【问题讨论】:

  • 这个方法public Date ConvertDate(Date date)是什么意思?
  • @vels4j 返回日期格式为 yyyy-MM-dd
  • @Oded 我只是赶时间,这就是为什么。对此感到抱歉。
  • @KeyBrdBasher 我认为它是重复的。输入格式不同,所以我在凝视时发现该链接
  • 上述链接中的输入是一个字符串,而你的是一个 Date 对象。看看下面的答案(和你选择的那个)我还是不明白这个问题对你没有帮助。

标签: java date simpledateformat date-formatting


【解决方案1】:

使用这个。

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

【讨论】:

  • +1 和新的 Date() 方法已被弃用。必须改用日历
  • @vels4j 为什么不分享代码以使用 Calendar 来替换已弃用的 Date 构造函数?
【解决方案2】:
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);

【讨论】:

    【解决方案3】:

    更新我的答案现在已经过时了。 Joda-Time 项目现在处于维护模式,建议迁移到 java.time 类。请参阅Answer by 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】:

      现代答案:使用来自java.timeLocalDate,现代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

      日期(无论是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 tutorial: Date Time,解释如何使用java.time

      【讨论】:

        【解决方案5】:

        您不能格式化Date 本身。您只能在String 中获取格式化结果。使用其他人提到的SimpleDateFormat

        而且,大部分getter methods in Datedeprecated.

        【讨论】:

          【解决方案6】:

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

          • 现代日期时间类型的日期时间格式化 API 在包中,java.time.format 例如java.time.format.DateTimeFormatterjava.time.format.DateTimeFormatterBuilder
          • 旧日期时间类型的日期时间格式化 API 在包中,java.text 例如java.text.SimpleDateFormatjava.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: Date Time 了解现代日期时间 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 对象不像modern date-time types 那样是真正的日期时间对象;相反,它表示距离Epoch of January 1, 1970 的毫秒数。当你打印一个java.util.Date 的对象时,它的toString 方法返回从这个毫秒值计算的日期时间。由于java.util.Date 没有时区信息,它会应用您的JVM 的时区并显示相同的信息。如果您需要在不同的时区打印日期时间,则需要将时区设置为 SimpleDateFomrat 并从中获取格式化字符串。
          2. java.util 的日期时间 API 及其格式 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到modern date-time API

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-06-24
            • 1970-01-01
            • 1970-01-01
            • 2023-03-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多