How to convert string to date object?

前端 未结 5 2162
不知归路
不知归路 2020-12-22 03:47
String date=\"2006-06-21T15:57:24.000Z\";

How do I convert this String to a Date object without changing this format in Android?

5条回答
  •  抹茶落季
    2020-12-22 04:32

    See SimpleDateFormat, http://developer.android.com/reference/java/text/SimpleDateFormat.html

    This class converts Strings to Dates and vice versa, using a given pattern.

    Once you have created a SimpleDateFormat with the right pattern, you can use it to convert the string to a Date, use the date as you like, and eventually convert the Date back to a String using that same SimpleDateFormat instance.

    EDIT: clarification on time zones

    In the question it is not specified wether the given string is a "pure" ISO 8601 date, and in that case whether you need or not to support multiple time zones, if that timezones will be represented as only numbers (+0200 as in RFC 822), numbers with a colon (+02:00 as permitted by ISO 8601) or as names (EST etc...).

    In case the string is a pure ISO 8601 String, then SimpleDateFormat will have some problems decoding the time zone. If however it is "always Z" (meaning that timezone data is not meaningful and you can safely ignore it), or uses numbers without colon (like +0200 etc..), or uses time zone names, then SimpleDateFormat can handle it correctly.

提交回复
热议问题