【问题标题】:How to convert Date to DateTime or LocalDate Joda如何将 Date 转换为 DateTime 或 LocalDate Joda
【发布时间】:2014-03-12 08:40:09
【问题描述】:

我在这个问题上花了两天时间。这是这个问题的延续:convert string to joda datetime gets stuck

我正在尝试执行一项简单的任务,即获取 SQL SERVER ISO 8601 字符串并将其转换为 DateTime 或 LocalDate。我尝试了所有方法,但是当涉及到使用调试器的实际转换时,程序光标只是在思考并且永远不会回来,即程序卡在那里。

我非常绝望,甚至尝试将该字符串转换为日期(有效!),然后将该日期转换为 DateTime 或 LocalDate。所有的结果都是一样的,在转换过程中,程序看起来像是陷入了无限循环(风扇开始疯狂地工作)。

这是我的简单功能:

    public static LocalDate SQLServerIso8601StringToLocalDate(String date) {

        LocalDate dateToReturn = null;
        DateFormat df = new SimpleDateFormat(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT);
        try {
            Date tempDate = (Date) df.parse(date);
            DateTime dt = new DateTime(tempDate);
            dateToReturn = new LocalDate(tempDate);

        } catch (ParseException e) {
            // strToReturn = strSqlDate;
        }
        return dateToReturn;

/*      
        date = date.replace('T', ' ');
        return SimpleIso8601StringToDateTime(date);
*/
        //return LocalDate.parse(date, DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT));

/*      DateTimeFormatter df = DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT_WITH_TZ);
        return df.parseDateTime(date);
*/  }

这是我的字符串:2014-01-01T00:00:00

还有:

public static final String SQL_SERVER_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

有什么想法吗?

【问题讨论】:

  • 您是否想说new LocalDate(tempDate); 让您的计算机永远忙碌,等于您输入的具体 java.util.Date?

标签: java datetime jodatime iso8601


【解决方案1】:
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;
}

【讨论】:

  • 谢谢。转换为 Date 有效。但我在 DateTime 或 LocalDate 中需要它,而这个卡住了程序。
  • public static String getDate(Date date, String dateFormat) { DateFormat formatter = new SimpleDateFormat(dateFormat);返回 formatter.format(date); }
  • 这是您需要的吗?你有日期对象,你可以做任何你想做的事
  • 日期数据类型非常有问题,在许多情况下没有用处。因此,当涉及到日期和时间时,强烈建议使用 Joda 的数据类型。我正在尝试将字符串转换为 DateTime 数据类型。
猜你喜欢
  • 2011-06-07
  • 2011-08-01
  • 1970-01-01
  • 2015-05-23
  • 2011-02-12
  • 2011-11-21
  • 1970-01-01
  • 2011-04-12
相关资源
最近更新 更多