【问题标题】:String("2013-4-25") to date conversionString("2013-4-25") 到日期转换
【发布时间】:2013-04-11 03:03:27
【问题描述】:

我有一个类似的字符串 "2013-4-25" 我需要将其转换为"MM-dd-yyyy" 格式。稍后我将不得不附加这个date 喜欢

Calendar cal=new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);

我怎么能这样做?

【问题讨论】:

  • 你使用哪种语言,顺便说一句?
  • Java。编辑了标签。

标签: java string date format


【解决方案1】:

您可以使用SimpleDateFormat。检查此链接:http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm

您可以指定您选择的格式化程序,然后相应地格式化日期。

【讨论】:

    【解决方案2】:

    使用JodaTimeDateMidnight 类,您不必自己规范日期。像这样的:

    DateTimeFormatter format = DateTimeFormatter.fromPattern("yyyy-MM-dd");
    DateMidnight date = DateMidnight.parse(date, format);
    

    JDK 中的 CalendarDate API 很痛苦...

    【讨论】:

      【解决方案3】:

      使用这个

      String str = "2013-4-25";
              SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
              try {
                  SimpleDateFormat parseFormatter = new SimpleDateFormat("yyyy-MM-dd");
      
                  Date date = parseFormatter.parse(str);
      
                  String formattedDate = formatter.format(date);
                  System.out.println(formattedDate);
              } catch (ParseException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
      

      【讨论】:

        【解决方案4】:

        使用SimpleDateFormat:

                Date date = new Date();
                Calendar cal=new GregorianCalendar();
                cal.setTime(date);
                cal.set(Calendar.HOUR, 23);
                cal.set(Calendar.MINUTE, 59);
                cal.set(Calendar.SECOND, 59);
        
                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
                System.out.println(sdf.format(cal.getTime()));
        

        【讨论】:

          猜你喜欢
          • 2013-04-19
          • 1970-01-01
          • 2016-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-11
          • 2019-02-28
          相关资源
          最近更新 更多