首页 文章

更改Java字符串中的日期格式

提问于
浏览
433

我有 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 . 我究竟做错了什么?

16 回答

  • 470

    请参考"Date and Time Patterns" . 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();
        }
      } 
    
    }
    
  • 9

    [编辑包含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();
    }
    
  • 6

    删除一个y表单 SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd"); 应为 SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

  • 4

    您可以尝试java 8 new 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);
        }
    
  • 137
    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");
      }
    
  • 5
    public class SystemDateTest {
    
        String stringDate;
    
        public static void main(String[] args) {
            SystemDateTest systemDateTest = new SystemDateTest();
            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;
        }
    }
    
  • 15

    如果字符串碰巧包含时区部分,则使用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
    

    Or ,当您还没有使用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
    

    另见:


    Update :根据您的尝试失败:模式为 case sensitive . 阅读java.text.SimpleDateFormat javadoc各个部分代表什么 . 因此,例如 M 表示月份, m 表示分钟 . 此外,存在四位数 yyyy ,而不是五位 yyyyy . 仔细看看我在上面发布的代码片段 .

  • 19

    格式化是CASE-SENSITIVE因此使用MM不是mm(这是分钟)和yyyy对于Reference你可以使用以下cheatsheet .

    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
    
  • 5

    为什么不简单地使用它

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

    干杯!

  • 8

    你也可以使用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);
    
  • 3

    你可以使用:

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

    它完美地运作!

  • 104

    答案当然是创建一个SimpleDateFormat对象并使用它来将字符串解析为Date并将Dates格式化为字符串 . 如果你已经尝试过SimpleDateFormat并且它不起作用,那么请显示你的代码以及你可能收到的任何错误 .

    附录:格式为String的“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));
        }
    
    }
    
  • 9
    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);
    };
    
  • 7
    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));
    
  • 3

    在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);
    
  • 8

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

    时区

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

    Joda-Time

    这是相同类型的代码,但使用第三方开源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
    

相关问题