【问题标题】:Function to convert String into Date [duplicate]将字符串转换为日期的函数[重复]
【发布时间】:2014-05-20 14:18:07
【问题描述】:

我编写了这段代码,用于将我从网页中提取的字符串转换为日期格式。但是每当我运行它时,它都会将月份转换为 01。

你能帮我调试一下这段代码吗?

    if (this.subject != null && !this.subject.isEmpty()) {
        DateFormat userDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        Date df = DATE_FORMAT.parse(this.subject);
        Calendar cal = Calendar.getInstance();
        cal.setTime(df);
        String theDate = String.format("%tY-%tm-%td", cal, cal, cal);
        return theDate;
    }

【问题讨论】:

  • Can you please help me debug this code? 为什么要我们调试这段代码?
  • 你为什么用String.format(..)而不是SimpleDateFormat

标签: java string function date


【解决方案1】:

试试这个代码这应该会有所帮助

if (this.subject != null && !this.subject.isEmpty()) {
    DateFormat userDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    DateFormat outDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    Date df = userDateFormat.parsethis.subject );
    return outDateFormat.format(df);
}

【讨论】:

    【解决方案2】:

    你不需要 GregorianCalendar(我希望你)。 就用这个吧:

    if (this.subject != null && !this.subject.isEmpty()) {
        DateFormat userDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        return userDateFormat.parse(this.subject);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 2012-07-30
      • 2012-11-25
      • 2011-08-30
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多