Convert date string to date android

Содержание
  1. How to convert a string to date in Java
  2. Java 8 Date & Time API
  3. Java 8 introduced a new date and time API (classes in java.time.* package) to make it easier to work with dates in Java. By default, these classes use ISO-8601 format to represent dates and times. parse() Method The new API provides the parse() method that accepts a sequence of characters as an argument and uses the ISO_LOCAL_DATE format to parse the string into a date: To convert a string into an instance of date using the above method, the string must be in ISO-8601 format. Otherwise, a DateTimeParseException will be thrown at runtime. Alternatively, you can pass another parameter to parse() to explicitly define the string pattern: A DateTimeFormatter instance is used as a formatter for formatting and parsing date-time objects in Java 8 new date and time API. Convert String to LocalDate The LocalDate class represents a date in ISO-8601 format (yyyy-MM-dd) without any time information. It is different from the old Date in the fact that it doesn’t store time or timezone information. Unlike Date , LocalDate provides utility methods to parse and format dates, add or subtract different units like days, months, and years. To parse an ISO-8601 string to an instance of LocalDate , you can do the following: The above code is equivalent of writing the following code to instantiate a LocalDate instance: If the string is not in ISO-8601 format, you must define a custom formatter using DateTimeFormatter as shown below: Here is another example that uses the pre-defined formatter BASIC_ISO_DATE from DateTimeFormatter to parse a string into a LocalDate : Convert String to LocalTime A LocalTime instance represents a time, without the date or timezone information in ISO-8601 format. Just like LocalDate , you can use LocalTime.parse() method to convert a string to a LocalTime object as shown below: The above code is equivalent of writing the following code to instantiate an instance of LocalTime : For non ISO-8601 string formats, you have to pass a formatter using DateTimeFormatter as shown below: Convert String to LocalDateTime The LocalDateTime class is the most popular class for handling date and time together in Java 8 and higher. It stores a combination of date and time without timezone in ISO-8601 format (yyyy-MM-ddTHH:mm). To parse an ISO-8601 string into an instance of LocalDateTime , you can simply use the parse() method as shown below: The above code is equivalent to the following code that instantiates an instance of LocalDateTime : To convert a string with a custom date format into a LocalDateTime object, you need to supply a formatter using DateTimeFormatter : Convert String to ZonedDateTime The ZonedDateTime class is used to deal with timezone specific dates and times. It represents a date-time with a timezone in the ISO-8601 format (e.g. 2010-05-15T10:15:30+01:00[Europe/Paris]). To convert an ISO-8601 string into an instance of ZonedDateTime , just use the parse() method: Convert String to OffsetDateTime The OffsetDateTime class represents a date and time with an offset from UTC/Greenwich in the ISO-8601 format (e.g. 1992-06-30T23:15:30-03:30). The following example demonstrates how you can convert an ISO-8601 string into an instance of OffsetDateTime : To parse custom strings into OffsetDateTime , you need to parse a custom formatter using DateTimeFormatter as shown below: Convert String to Instant The Instant class represents a specific moment on the timeline. To convert a string into an Instant object, the string must be in ISO_INSTANT format (e.g. 2011-12-03T10:15:30Z). Here is an example: You can easily convert an Instant object to any other date-time format like LocalDateTime or ZonedDateTime : Here is the output of the above code snippet: Convert String to java.util.Date Before Java 8, both java.util.Date and java.util.Calendar classes were used to handle dates and times. These classes are not actively used today but they are still worth covering as most of the legacy codes are still using them. To convert a string into an instance of Date , you need to use the SimpleDateFormat class to define a custom date and time pattern. Here are a few examples: The above code generates the following output: By default, Date doesn’t contain any information about the timezone. Therefore, it is not possible to set a timezone for a Date object. When we convert a string to Date using SimpleDateFormat.parse() , it is automatically converted to the default system timezone. For example, look at the last string to date conversion in the example above. The 2018-10-05T15:23:01Z date-time string in UTC (with time 15:23:01 ) is converted to Fri Oct 05 20:23:01 PKT 2018 with time 20:23:01 . This is because the PKT is 5 hours ahead of UTC (+05:00). However, you can format the Date object and add the timezone information to a string using SimpleDateFormat : Here is the output of the above code: DateTimeFormatter vs SimpleDateFormat After learning string to date conversion through both Java 8 new date and time API’s DateTimeFormatter and SimpleDateFormat , you may be wondering «how do they differ from each other, and what is the right choice for me?» Introduced in Java 8 with the new date and time API, DateTimeFormatter is a part of java.time.format.* that replaces the older and less frequently used SimpleDateFormat . Both these classes are used to declare a date and time pattern for parsing and formatting dates and times. The DateTimeFormatter class is thread-safe unlike its older counterpart and offers new utility methods and constants for various date and time formats. Let us look at the below example: As you can see above, the difference between DateTimeFormatter and SimpleDateFormat is very much clear. In the new date and time API, the classes have their own parse and format methods and use DateTimeFormatter for the sake of defining patterns only. In the older API, a formatter is used to both parse and format the date. Rule of thumb, use DateTimeFormatter if you are using Java 8 new date and time API. For legacy codebase (Java 7 and below), use SimpleDateFormat for patterns. 3rd-Party Libraries Now that we have developed a good understanding of performing string to date conversion using both new and old APIs included in core Java, let us look at some external libraries. Joda-Time Before Java 8, Joda-Time was developed to overcome the shortcomings of old date and time API. It provided an excellent alternative to core Java date and time classes and quickly became a de facto standard date and time library for Java before Java SE 8. As of Java 8, all of its functionality is already implemented in the core Java in the form of the new date and time API. That is why the author of Joda-Time recommends users to migrate to Java 8 java.time (JSR-310) for working with dates and times. In case if the migration is not possible, or if you are still using Java 7 or below, Joda-Time is still a great library to use. To add Joda-Time to your Maven project, add the following dependency to pom.xml file: For a Gradle project, include the below dependency to your build.gralde file: Working with Joda-Time is very much similar to working with Java 8 new date and time API. Here is a quick example: The DateTime class from Joda-Time also supports the timezone information: Apache Commons Lang The Apache Commons Lang library is another important 3rd-party library that provides many useful utility classes for working with legacy Date and Calendar classes. To add the library to your Maven project, add the following dependency to pom.xml file: For Gradle, add the below dependency to your build.gradle file: Now you can use the DateUtils class from Apache Commons Lang to parse a string into a Date object: As you can see above, DateUtils.parseDate() accepts an array of patterns. It will parse each pattern after another. If no pattern matches the given input string, it throws a ParseException exception. Common Date and Time Patterns Let us take a look at some of the most common patterns that you can use with DateTimeFormatter and SimpleDateFormat for formatting and parsing dates and times: Letter Description Examples y Year 2019 M Month in year August, 08, 8 d Day in month 1-31 E Day name in week Monday, Friday a Ante meridiem/Post meridiem marker AM, PM H Hour in day 0-23 h Hour in AM/PM 1-12 m Minute in hour 0-60 s Second in minute 0-60 S Millisecond in the minute 978 z Timezone Pacific Standard Time; PST; GMT-08:00 Z Timezone offset in hours (RFC pattern) -0800 X Timezone offset in ISO format -08; -0800; -08:00 s Second in minute 0-60 Look at this JavaDoc for a full list of symbols that you can use to define a date and time pattern for parsing a string into a date. Summary String to date conversion is one of the most frequent operations in Java. In this article, we have covered multiple ways to convert a string object into a date object including Java 8 new date and time API, legacy Date class, 3rd-party libraries like Joda-Time and Apache Commons Lang. The new date and time API provides an extensive set of classes for parsing different types of strings into the newest API date and time objects. These classes are thread-safe, backward-compatible, and easier-to-use. You should always use the new API for parsing and formatting dates and times in Java 8 and higher. If, for some reason, you cannot use the new API, go for the Joda-Time library. It is an excellent replacement of core Java date and time API before Java 8. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed. Источник How to Convert a String to Date in Java Converting a string to a date in Java (or any programming language) is a fundamental skill and is useful to know when working on projects. Sometimes, it’s simply easier to work with a string to represent a date, and then convert it into a Date object for further use. In this article, we’ll go over the many methods and libraries you can use to convert a Java string into a date object. The Date/Time API The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you’re using the default formatter. parse() This API defines a parse() method that accepts a sequence of characters and uses the ISO_LOCAL_DATE format to parse the input: Alternatively, you can use the two-argument variant of this method, defining a different formatter: A DateTimeFormatter is used for formatting and parsing date-time objects in the new Date/Time API. All date-time classes from this API contain a method for parsing and formatting, where each accepts a DateTimeFormatter to define a pattern. Converting a String to LocalDate A LocalDate represents a date, without time in ISO-8601 format. It differs from Date in the fact that it doesn’t store time as a millisecond offset since epoch, but rather simply the current date. It’s also a newer implementation from the Date/Time API and offers its own format/parse method, as well as addition and subtraction of days, weeks and years, which doesn’t exist in the Date variant. To convert a string to a LocalDate object, it’s enough to write: This is the equivalent of writing the proceeding code to instantiate a LocalDate object: Converting a String to LocalTime LocalTime represents time, without a time-zone in ISO-8601 format. It doesn’t store time based on the offset since epoch, and it offers nanosecond precision. Just like the LocalDate, it provides a lot of very useful parsing and formatting methods built in, as well as the means to add or subtract time from it. To convert a string to a LocalTime object, it’s enough to write: This is the equivalent of writing the proceeding code to instantiate a LocalTime object: Converting a String to LocalDateTime The LocalDateTime is the most used class regarding Date/Time in Java. It represents a combination of date and time, and can be used for many purposes: This format may seem confusing at first, but it’s actually rather simple: The «Time» marker simply represents a line between the LocalDate and LocalTime parts of the format. You can also easily format this LocalDateTime into a more readable format: Running this piece of code and printing formatDateTime would yield: You would typically do this to show the result to the end user in string format, while performing operations on the LocalDateTime object beforehand. Converting a String to ZonedDateTime Depending on the project you’re working on you might need to handle different time zones when dealing with dates and time. Converting a String to a ZonedDateTime object is as simple as: The example above shows how you would initialize a ZonedDateTime for London. Converting a String using a Custom Formatter Sometimes, we could wish to use our own custom formatter, that accepts a string in the most varied ways and still not throw a DateTimeParseException . Free eBook: Git Essentials Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it! Here are some of the most common patterns you would use: y : Year (2018, 18) M : Month in a year (August, Aug, 08) d : Day in a month (1, 5, 25) E : Name of a day in a week (Monday, Saturday) a : Ante meridiem/Post meridiem marker (AM, PM) H : Hour in a 24h style (1, 7, 14, 21) h : Hour in a 12h style (1, 5, 12) m : Minute in an hour (1, 25, 54) s : Second in a minute (1, 25, 54) And some you might not use that often: G : Era designator (AD, CE) Y : Week year (2018, 18) w : Week in a a year (25, 53) W : Week in a month (2) D : Day in a year (254) F : Day of week in a month (3) E : Day name in a week (Monday, Mon) u : Day number of a week (1, 4) k : Hour in a day (17) K : Hour in a day in AM/PM (5) S : Millisecond (1245) z : General Time Zone (Pacific Standard Time;PST;GMT-8:00) Z : RFC 822 Time Zone (-0800) X : ISO 8601 Time Zone (-08, -0800, -8:00) Note: Week year differs from a year — A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values. Note: K and H differ the same way k and h differ. H and h refer to the 0-23 and 1-12 model respectively, while K and k refer to the 0-11 and 1-24 respectively. If this still doesn’t satisfy your need for a custom formatter, you can use DateTimeFormatterBuilder to build very specific and complex formatters. Amongst other things, DateTimeFormatter is built using this class. java.util.Date This is an older approach, which isn’t used often today, but it’s still worth covering since sometimes we still use the classes from these APIs: There are many patterns that we can pass into the constructor of SimpleDateFormat . You can combine pretty much any number of formats using the available patterns. It’s not possible to set a timezone for a Date, because it simply doesn’t contain such information. However, it’s easy to format the date and add the timezone information to a String: Running this piece of code will yield: «22:23:43 CEST» corresponds to the «10:23:43PM» time, while the formatted date represents «8:23:43 PM» since it’s in a different time zone. SimpleDateFormat vs DateTimeFormatter Reading this article, it’s fair to raise the question — «What is the difference, and which one should I be using?« DateTimeFormatter has been added in Java 8 with the new Date/Time API, and replaces the older, now less frequently used SimpleDateFormat . It’s thread-safe unlike its older counterpart and offers new functionality: It’s clear to see the difference between these two. In the older way, a formatter is used to format and then parse the date. In the newer way, dates have their own format and parse methods and use a DateTimeFormatter simply for the pattern. If you’re using Java 8 and the new API, use DateTimeFormatter, whereas if you’re still using an older version of Java, use SimpleDateFormat. Joda-Time Joda-Time was developed to counter the problems with the old Java time and date classes. As of Java 8, these problems have been corrected, and Joda-Time has served its purpose. Even the authors of it advise migrating to official java.time to work with dates and time. In the case that this is impossible, and for those who still use a version of Java prior to Java 8, Joda-Time is still a great library to use. A dependency for this library can easily be added with a Maven dependency: Working with Joda-Time is very similar to working with Java’s Date/Time API: Joda-Time’s DateTime class supports timezones as well: For a full list of time zone IDs available for use, visit the official docs. Apache Commons Apache Commons is a useful library used in many projects. To add this library to your project, you can use the Maven dependency: Both of the implementations below accept an array of patterns. These methods will parse each pattern after another. If no pattern matches the input string, a ParseException is thrown. Using DateTimeConverter Using DateUtils Conclusion We’ve covered multiple ways to convert a simple String into Date and Date-Time classes in Java. Some of these approaches utilize third-party libraries which you might already have in your project, and some are done utilizing the APIs Java offers. Источник
  4. parse() Method
  5. Convert String to LocalDate
  6. Convert String to LocalTime
  7. Convert String to LocalDateTime
  8. Convert String to ZonedDateTime
  9. Convert String to OffsetDateTime
  10. Convert String to Instant
  11. Convert String to java.util.Date
  12. DateTimeFormatter vs SimpleDateFormat
  13. 3rd-Party Libraries
  14. Joda-Time
  15. Apache Commons Lang
  16. Common Date and Time Patterns
  17. Summary
  18. How to Convert a String to Date in Java
  19. The Date/Time API
  20. parse()
  21. Converting a String to LocalDate
  22. Converting a String to LocalTime
  23. Converting a String to LocalDateTime
  24. Converting a String to ZonedDateTime
  25. Converting a String using a Custom Formatter
  26. Free eBook: Git Essentials
  27. java.util.Date
  28. SimpleDateFormat vs DateTimeFormatter
  29. Joda-Time
  30. Apache Commons
  31. Using DateTimeConverter
  32. Using DateUtils
  33. Conclusion
Читайте также:  Почему часы амазфит не синхронизируются с телефоном андроид

How to convert a string to date in Java

декабря 22, 2019 • Atta

String to date conversion is one of the most frequent tasks in Java or any other programming language. It is useful to know how to perform string to date conversion before working on Java projects.

In this tutorial, you’ll learn about different ways to convert a string object to a date object in Java. We’ll first look at utility methods provided by Java 8 new date and time API to perform string to date conversion. Afterward, we’ll also look at the legacy java.util.Date class that is also used to represent dates. Finally, we’ll discuss 3rd-party libraries like Apache Commons Lang that can also be used to perform this conversion.

Java 8 Date & Time API
  • Java 8 introduced a new date and time API (classes in java.time.* package) to make it easier to work with dates in Java. By default, these classes use ISO-8601 format to represent dates and times.

    parse() Method

  • The new API provides the parse() method that accepts a sequence of characters as an argument and uses the ISO_LOCAL_DATE format to parse the string into a date:

    To convert a string into an instance of date using the above method, the string must be in ISO-8601 format. Otherwise, a DateTimeParseException will be thrown at runtime.

    Alternatively, you can pass another parameter to parse() to explicitly define the string pattern:

    A DateTimeFormatter instance is used as a formatter for formatting and parsing date-time objects in Java 8 new date and time API.

    Convert String to LocalDate

  • The LocalDate class represents a date in ISO-8601 format (yyyy-MM-dd) without any time information. It is different from the old Date in the fact that it doesn’t store time or timezone information. Unlike Date , LocalDate provides utility methods to parse and format dates, add or subtract different units like days, months, and years.

    To parse an ISO-8601 string to an instance of LocalDate , you can do the following:

    The above code is equivalent of writing the following code to instantiate a LocalDate instance:

    If the string is not in ISO-8601 format, you must define a custom formatter using DateTimeFormatter as shown below:

    Here is another example that uses the pre-defined formatter BASIC_ISO_DATE from DateTimeFormatter to parse a string into a LocalDate :

    Convert String to LocalTime

  • A LocalTime instance represents a time, without the date or timezone information in ISO-8601 format. Just like LocalDate , you can use LocalTime.parse() method to convert a string to a LocalTime object as shown below:

    The above code is equivalent of writing the following code to instantiate an instance of LocalTime :

    For non ISO-8601 string formats, you have to pass a formatter using DateTimeFormatter as shown below:

    Convert String to LocalDateTime

  • The LocalDateTime class is the most popular class for handling date and time together in Java 8 and higher. It stores a combination of date and time without timezone in ISO-8601 format (yyyy-MM-ddTHH:mm).

    To parse an ISO-8601 string into an instance of LocalDateTime , you can simply use the parse() method as shown below:

    The above code is equivalent to the following code that instantiates an instance of LocalDateTime :

    To convert a string with a custom date format into a LocalDateTime object, you need to supply a formatter using DateTimeFormatter :

    Convert String to ZonedDateTime

  • The ZonedDateTime class is used to deal with timezone specific dates and times. It represents a date-time with a timezone in the ISO-8601 format (e.g. 2010-05-15T10:15:30+01:00[Europe/Paris]).

    To convert an ISO-8601 string into an instance of ZonedDateTime , just use the parse() method:

    Convert String to OffsetDateTime

  • The OffsetDateTime class represents a date and time with an offset from UTC/Greenwich in the ISO-8601 format (e.g. 1992-06-30T23:15:30-03:30).

    The following example demonstrates how you can convert an ISO-8601 string into an instance of OffsetDateTime :

    To parse custom strings into OffsetDateTime , you need to parse a custom formatter using DateTimeFormatter as shown below:

    Convert String to Instant

  • The Instant class represents a specific moment on the timeline. To convert a string into an Instant object, the string must be in ISO_INSTANT format (e.g. 2011-12-03T10:15:30Z).

    Here is an example:

    You can easily convert an Instant object to any other date-time format like LocalDateTime or ZonedDateTime :

    Here is the output of the above code snippet:

    Convert String to java.util.Date

  • Before Java 8, both java.util.Date and java.util.Calendar classes were used to handle dates and times. These classes are not actively used today but they are still worth covering as most of the legacy codes are still using them.

    To convert a string into an instance of Date , you need to use the SimpleDateFormat class to define a custom date and time pattern. Here are a few examples:

    The above code generates the following output:

    By default, Date doesn’t contain any information about the timezone. Therefore, it is not possible to set a timezone for a Date object. When we convert a string to Date using SimpleDateFormat.parse() , it is automatically converted to the default system timezone.

    For example, look at the last string to date conversion in the example above. The 2018-10-05T15:23:01Z date-time string in UTC (with time 15:23:01 ) is converted to Fri Oct 05 20:23:01 PKT 2018 with time 20:23:01 . This is because the PKT is 5 hours ahead of UTC (+05:00).

    However, you can format the Date object and add the timezone information to a string using SimpleDateFormat :

    Here is the output of the above code:

    DateTimeFormatter vs SimpleDateFormat

  • After learning string to date conversion through both Java 8 new date and time API’s DateTimeFormatter and SimpleDateFormat , you may be wondering «how do they differ from each other, and what is the right choice for me?»

    Introduced in Java 8 with the new date and time API, DateTimeFormatter is a part of java.time.format.* that replaces the older and less frequently used SimpleDateFormat . Both these classes are used to declare a date and time pattern for parsing and formatting dates and times.

    The DateTimeFormatter class is thread-safe unlike its older counterpart and offers new utility methods and constants for various date and time formats.

    Let us look at the below example:

    As you can see above, the difference between DateTimeFormatter and SimpleDateFormat is very much clear. In the new date and time API, the classes have their own parse and format methods and use DateTimeFormatter for the sake of defining patterns only. In the older API, a formatter is used to both parse and format the date.

    Rule of thumb, use DateTimeFormatter if you are using Java 8 new date and time API. For legacy codebase (Java 7 and below), use SimpleDateFormat for patterns.

    3rd-Party Libraries

  • Now that we have developed a good understanding of performing string to date conversion using both new and old APIs included in core Java, let us look at some external libraries.

    Joda-Time

  • Before Java 8, Joda-Time was developed to overcome the shortcomings of old date and time API. It provided an excellent alternative to core Java date and time classes and quickly became a de facto standard date and time library for Java before Java SE 8.

    As of Java 8, all of its functionality is already implemented in the core Java in the form of the new date and time API. That is why the author of Joda-Time recommends users to migrate to Java 8 java.time (JSR-310) for working with dates and times.

    In case if the migration is not possible, or if you are still using Java 7 or below, Joda-Time is still a great library to use.

    To add Joda-Time to your Maven project, add the following dependency to pom.xml file:

    For a Gradle project, include the below dependency to your build.gralde file:

    Working with Joda-Time is very much similar to working with Java 8 new date and time API. Here is a quick example:

    The DateTime class from Joda-Time also supports the timezone information:

    Apache Commons Lang

  • The Apache Commons Lang library is another important 3rd-party library that provides many useful utility classes for working with legacy Date and Calendar classes.

    To add the library to your Maven project, add the following dependency to pom.xml file:

    For Gradle, add the below dependency to your build.gradle file:

    Now you can use the DateUtils class from Apache Commons Lang to parse a string into a Date object:

    As you can see above, DateUtils.parseDate() accepts an array of patterns. It will parse each pattern after another. If no pattern matches the given input string, it throws a ParseException exception.

    Common Date and Time Patterns

  • Let us take a look at some of the most common patterns that you can use with DateTimeFormatter and SimpleDateFormat for formatting and parsing dates and times:

    Letter Description Examples
    y Year 2019
    M Month in year August, 08, 8
    d Day in month 1-31
    E Day name in week Monday, Friday
    a Ante meridiem/Post meridiem marker AM, PM
    H Hour in day 0-23
    h Hour in AM/PM 1-12
    m Minute in hour 0-60
    s Second in minute 0-60
    S Millisecond in the minute 978
    z Timezone Pacific Standard Time; PST; GMT-08:00
    Z Timezone offset in hours (RFC pattern) -0800
    X Timezone offset in ISO format -08; -0800; -08:00
    s Second in minute 0-60

    Look at this JavaDoc for a full list of symbols that you can use to define a date and time pattern for parsing a string into a date.

    Summary

  • String to date conversion is one of the most frequent operations in Java. In this article, we have covered multiple ways to convert a string object into a date object including Java 8 new date and time API, legacy Date class, 3rd-party libraries like Joda-Time and Apache Commons Lang.

    The new date and time API provides an extensive set of classes for parsing different types of strings into the newest API date and time objects. These classes are thread-safe, backward-compatible, and easier-to-use. You should always use the new API for parsing and formatting dates and times in Java 8 and higher.

    If, for some reason, you cannot use the new API, go for the Joda-Time library. It is an excellent replacement of core Java date and time API before Java 8.

    ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

    Источник

    How to Convert a String to Date in Java

    Converting a string to a date in Java (or any programming language) is a fundamental skill and is useful to know when working on projects. Sometimes, it’s simply easier to work with a string to represent a date, and then convert it into a Date object for further use.

    In this article, we’ll go over the many methods and libraries you can use to convert a Java string into a date object.

    The Date/Time API

    The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) .

    All Dates by default follow this format, and all Strings that are converted must follow it if you’re using the default formatter.

    parse()

    This API defines a parse() method that accepts a sequence of characters and uses the ISO_LOCAL_DATE format to parse the input:

    Alternatively, you can use the two-argument variant of this method, defining a different formatter:

    A DateTimeFormatter is used for formatting and parsing date-time objects in the new Date/Time API. All date-time classes from this API contain a method for parsing and formatting, where each accepts a DateTimeFormatter to define a pattern.

    Converting a String to LocalDate

    A LocalDate represents a date, without time in ISO-8601 format.

    It differs from Date in the fact that it doesn’t store time as a millisecond offset since epoch, but rather simply the current date. It’s also a newer implementation from the Date/Time API and offers its own format/parse method, as well as addition and subtraction of days, weeks and years, which doesn’t exist in the Date variant.

    To convert a string to a LocalDate object, it’s enough to write:

    This is the equivalent of writing the proceeding code to instantiate a LocalDate object:

    Converting a String to LocalTime

    LocalTime represents time, without a time-zone in ISO-8601 format. It doesn’t store time based on the offset since epoch, and it offers nanosecond precision.

    Just like the LocalDate, it provides a lot of very useful parsing and formatting methods built in, as well as the means to add or subtract time from it.

    To convert a string to a LocalTime object, it’s enough to write:

    This is the equivalent of writing the proceeding code to instantiate a LocalTime object:

    Converting a String to LocalDateTime

    The LocalDateTime is the most used class regarding Date/Time in Java. It represents a combination of date and time, and can be used for many purposes:

    This format may seem confusing at first, but it’s actually rather simple:

    The «Time» marker simply represents a line between the LocalDate and LocalTime parts of the format.

    You can also easily format this LocalDateTime into a more readable format:

    Running this piece of code and printing formatDateTime would yield:

    You would typically do this to show the result to the end user in string format, while performing operations on the LocalDateTime object beforehand.

    Converting a String to ZonedDateTime

    Depending on the project you’re working on you might need to handle different time zones when dealing with dates and time.

    Converting a String to a ZonedDateTime object is as simple as:

    The example above shows how you would initialize a ZonedDateTime for London.

    Converting a String using a Custom Formatter

    Sometimes, we could wish to use our own custom formatter, that accepts a string in the most varied ways and still not throw a DateTimeParseException .

    Free eBook: Git Essentials

    Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

    Here are some of the most common patterns you would use:

    • y : Year (2018, 18)
    • M : Month in a year (August, Aug, 08)
    • d : Day in a month (1, 5, 25)
    • E : Name of a day in a week (Monday, Saturday)
    • a : Ante meridiem/Post meridiem marker (AM, PM)
    • H : Hour in a 24h style (1, 7, 14, 21)
    • h : Hour in a 12h style (1, 5, 12)
    • m : Minute in an hour (1, 25, 54)
    • s : Second in a minute (1, 25, 54)

    And some you might not use that often:

    • G : Era designator (AD, CE)
    • Y : Week year (2018, 18)
    • w : Week in a a year (25, 53)
    • W : Week in a month (2)
    • D : Day in a year (254)
    • F : Day of week in a month (3)
    • E : Day name in a week (Monday, Mon)
    • u : Day number of a week (1, 4)
    • k : Hour in a day (17)
    • K : Hour in a day in AM/PM (5)
    • S : Millisecond (1245)
    • z : General Time Zone (Pacific Standard Time;PST;GMT-8:00)
    • Z : RFC 822 Time Zone (-0800)
    • X : ISO 8601 Time Zone (-08, -0800, -8:00)

    Note: Week year differs from a year — A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.

    Note: K and H differ the same way k and h differ. H and h refer to the 0-23 and 1-12 model respectively, while K and k refer to the 0-11 and 1-24 respectively.

    If this still doesn’t satisfy your need for a custom formatter, you can use DateTimeFormatterBuilder to build very specific and complex formatters. Amongst other things, DateTimeFormatter is built using this class.

    java.util.Date

    This is an older approach, which isn’t used often today, but it’s still worth covering since sometimes we still use the classes from these APIs:

    There are many patterns that we can pass into the constructor of SimpleDateFormat . You can combine pretty much any number of formats using the available patterns.

    It’s not possible to set a timezone for a Date, because it simply doesn’t contain such information. However, it’s easy to format the date and add the timezone information to a String:

    Running this piece of code will yield:

    «22:23:43 CEST» corresponds to the «10:23:43PM» time, while the formatted date represents «8:23:43 PM» since it’s in a different time zone.

    SimpleDateFormat vs DateTimeFormatter

    Reading this article, it’s fair to raise the question — «What is the difference, and which one should I be using?«

    DateTimeFormatter has been added in Java 8 with the new Date/Time API, and replaces the older, now less frequently used SimpleDateFormat . It’s thread-safe unlike its older counterpart and offers new functionality:

    It’s clear to see the difference between these two. In the older way, a formatter is used to format and then parse the date. In the newer way, dates have their own format and parse methods and use a DateTimeFormatter simply for the pattern.

    If you’re using Java 8 and the new API, use DateTimeFormatter, whereas if you’re still using an older version of Java, use SimpleDateFormat.

    Joda-Time

    Joda-Time was developed to counter the problems with the old Java time and date classes.

    As of Java 8, these problems have been corrected, and Joda-Time has served its purpose. Even the authors of it advise migrating to official java.time to work with dates and time.

    In the case that this is impossible, and for those who still use a version of Java prior to Java 8, Joda-Time is still a great library to use.

    A dependency for this library can easily be added with a Maven dependency:

    Working with Joda-Time is very similar to working with Java’s Date/Time API:

    Joda-Time’s DateTime class supports timezones as well:

    For a full list of time zone IDs available for use, visit the official docs.

    Apache Commons

    Apache Commons is a useful library used in many projects.

    To add this library to your project, you can use the Maven dependency:

    Both of the implementations below accept an array of patterns. These methods will parse each pattern after another. If no pattern matches the input string, a ParseException is thrown.

    Using DateTimeConverter

    Using DateUtils

    Conclusion

    We’ve covered multiple ways to convert a simple String into Date and Date-Time classes in Java. Some of these approaches utilize third-party libraries which you might already have in your project, and some are done utilizing the APIs Java offers.

    Источник

  • Оцените статью