将字符串日期解析为 joda DateTime

parse string date to jodaDateTime

我在将字符串日期转换为 joda DateTime 对象时遇到问题

我的日期格式是

   fromDate:2015-10-16T00:00:00.000+05:30
   toDate:2015-10-17T00:00:00.000+05:30

我不知道要使用哪种日期格式模式,将其转换为日期时间对象,当我有像这样的单独整数时我可以转换

       fromDate = new DateTime().withDate(params?.fromDate_year.toInteger(), params?.fromDate_month.toInteger(), params?.fromDate_day.toInteger()).withTimeAtStartOfDay()
        toDate =  new DateTime().withDate(params?.toDate_year.toInteger(), params?.toDate_month.toInteger(), params?.toDate_day.toInteger()).withTimeAtStartOfDay()

如何将我的字符串转换为日期?

这样做很简单,joda 库会为你处理一切,你只需要将字符串日期传递给 DateTime()

  String fromDate = "2015-10-16T00:00:00.000+05:30"
  String toDate = "2015-10-17T00:00:00.000+05:30"
  fromDate = new DateTime(fromDate);
  toDate = new DateTime(toDate);

干杯!

继续@roanjain 所说的,Joda 会很好地解析这样的字符串,但是,创建的 DateTime 对象将显示默认时区。如果您的计算机不在 "Asia/Kolkata" 时区,您需要告诉 Joda 您想要该时区的 DateTime,如下所示:

public static void main(String[] args) {
    String time = "2015-10-16T00:00:00.000+05:30";
    DateTime dt = new DateTime(time);
    // Will show whatever time zone you are in
    System.out.println(dt);
    // Same point in time, but represented in a different time zone
    System.out.println(dt.withZone(DateTimeZone.forID("Asia/Kolkata")));
    // Create a DateTime object in the requested timezone
    dt = new DateTime(time).withZone(DateTimeZone.forID("Asia/Kolkata"));
    System.out.println(dt);
}

请注意,两个时间戳代表相同的时间点,并且将保持适当的可比性。