简体   繁体   中英

Initializing Date Object in java from a given string representation

I am trying to import a given string representing a Date in the format:

2007-03-12T00:00:00.000+01:00 

Now to create a new Date Object i use Joda Library using:

DateTime date = new DateTime(year, month, day, hour, minute, second);

However, i want to make sure two things here:

  • How to handle GTM +1 in this date time context?
  • Is there anyway, that i don't have to parse this string, and the Date Object can be initialized directly with this string?
DateTime date = DateTime.parse("2007-03-12T00:00:00.000+01:00");

正如在其他答案中提到的那样,应该根据文档将偏移量与字符串的其余部分一起解析。

You can parse that date string using SimpleDateFormat , then pass that Date into a Joda class:

String dateStr = "2007-03-12T00:00:00.000+01:00";
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = sdf.parse( dateStr.replaceAll(":(?=..$)", "")); // remove last colon

Note that you must remove the last colon so the offset is a RFC 822 time zone like +0100 , which I did using String.replaceAll()

Both your questions can be answered by reading the documentation for the class

timezone is handled by the class. Look for the constructor which takes the timezone argument.

Yes you can create the DateTime object using the string. DateTime.parse(String) is available to do that. There is also another method available to parse custom date formats if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM