Java date to iso8601

Data Type Conversions in Java

In this tutorial, we will focus on type conversion for primitive data types.

String to int

There are two methods available for String to int conversion: Integer.parseInt() which returns a primitive int and Integer.valueOf() which return an Integer object.

String str = "1050"; int inum = Integer.parseInt(str); //return primitive System.out.println(inum); Integer onum = Integer.valueOf(str); //return object System.out.println(onum); 

String to long

Similar to int , we can convert a String into a primitive long value using Long.parseLong() or an object Long via Long.valueOf() method.

String longStr = "1456755"; long ilong = Long.parseLong(longStr); //return primitive System.out.println(ilong); Long olong = Long.valueOf(longStr); //return object System.out.println(olong); 

String to float

A String can be converted to primitive float value using Float.parseFloat() method. Float.valueOf() method can be used to convert a String into a Float object.

String floatStr = "49.78"; float ifloat = Float.parseFloat(floatStr); //return primitive System.out.println(ifloat); Float ofloat = Float.valueOf(floatStr); //return object System.out.println(ofloat); 

String to double

double and float data types may look same but are different in the way that they store the value. float is a single precision (32 bit or 4 bytes) floating point data type whereas double is a double precision (64 bit or 8 bytes) floating point data type.

A String value can be converted to double value using Double.parseDouble() method. Similarly, Double.valueOf() converts a String into a Double object.

String doubleStr = "99.378"; double idouble = Double.parseDouble(doubleStr); //return primitive System.out.println(idouble); Double odouble = Double.valueOf(doubleStr); //return object System.out.println(odouble); 

NumberFormatException

If the String does not contain a parsable value during int , float , or double conversion, a NumberFormatException is thrown.

try  String exeStr = "14c"; int exeInt = Integer.parseInt(exeStr); System.out.println(exeInt); > catch (NumberFormatException ex)  System.out.println(ex.getMessage()); > 

String to boolean

A String value can be converted to primitive boolean value using Boolean.parseBoolean method. For conversion to Boolean object, you can use Boolean.valueOf() method.

String trueStr = "true"; String falseStr = "false"; String randomStr = "java"; System.out.println(Boolean.parseBoolean(trueStr)); //true System.out.println(Boolean.valueOf(falseStr)); //false System.out.println(Boolean.parseBoolean(randomStr)); //false 

String to Date

Java provides SimpleDateFormat class for formatting and parsing dates. It has the following two important method:

  • parse() — It converts a String value into a Date object
  • format() — It converts the Date object into a String value

While creating an instance of the SimpleDateFormat classes, you need to pass date and time pattern that tells how the instance should parse or format the dates.

String dateStr = "10/03/2019"; SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date dateObj = format.parse(dateStr); System.out.println(dateObj); 

In the example above, I used dd/MM/yyyy pattern to parse 10/03/2019 string. dd means two digits for the day, MM means two digit for the month and yyyy means 4 digits for the year. Below is a list of the most common date and time patterns used in SimpleDateFormat . For the complete list, please refer to official JavaDoc.

Letter Description Examples
y Year 2019, 19
M Month in year March, Mar, 03, 3
d Day in month 1-31
E Date name in week Friday-Sunday
a Am/pm marker AM, PM
H Hour in day 0-23
h Hour in am/pm 1-12
m Minute in hour 0-59
s Second in minute 0-59
S Millisecond in second 0-999
z General timezone Central European Time, PST, GMT +05:00

Following are some pattern examples, with examples of how each pattern would parse a date or vice versa:

yyyy/MM/dd (2019/03/09) dd-MM-YYYY (10-03-2019) dd-MMM-yy (13-Feb-19) EEE, MMMM dd, yyy (Fri, March 09, 2019) yyyy-MM-dd HH:mm:ss (2019-02-28 16:45:23) hh:mm:ss a (11:23:36 PM) yyyy-MM-dd HH:mm:ss.SSS Z (2019-01-31 21:05:46.555 +0500) 

Date to String

As we discussed above, SimpleDateFormat also supports formatting of dates into strings. Here is an example that formats the date into a string:

Date date = Calendar.getInstance().getTime(); // OR new Date() SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy HH:mm:ss.SSS Z"); String formatStr = dateFormat.format(date); System.out.println(formatStr); 

The above code snippet will print the following depending on your location:

Sunday, March 10, 2019 20:01:22.417 +0500 

Date to ISO 8601 String

ISO 8601 is an international standard that covers the exchange of date- and time-related data. There ere several ways to express date and time in ISO format:

2019-03-30T14:22:15+05:00 2019-03-30T09:22:15Z 20190330T092215Z 

Here is an example to convert a date object into an ISO 8601 equivalent string in Java:

TimeZone timeZone = TimeZone.getTimeZone("UTC"); SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); isoFormat.setTimeZone(timeZone); String isoFormatStr = isoFormat.format(new Date()); System.out.println(isoFormatStr); 

Following are the date and time patterns for ISO format:

Pattern ISO Date Format
yyyy-MM-dd’T’HH:mm:ssXXX 2019-03-30T14:22:15+05:00
yyyy-MM-dd’T’HH:mm:ss’Z’ 2019-03-30T09:22:15Z
yyyyMMdd’T’HHmmss’Z’ 20190330T092215Z

Source code: Download the complete source code from GitHub available under MIT license.

Conclusion

Data type conversions are very common for a developer. Most of these conversions are trivial and are well-known to an experienced programmer. However, string to date conversion is a bit tricky especially for beginners. You may encounter errors if the pattern is not specified correctly. But if you spend some time to remember these patterns, it may save a lot of time while figuring out why a certain conversion is not compiling or executing.

Am I missing any important type conversion in this tutorial? Send me a tweet any time to let me know.

✌️ I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter to get web development tutorials & protips every week.

Источник

Convert Date to ISO 8601 String in Java

Convert Java dates to ISO-8601 string: this post explains how to convert java.util.Date, java.util.Calendar, java.time.ZonedDateTime to string.

In Java, converting date objects to string is difficult, because the built-in APIs are similar and confusing. However, as a developer, we cannot avoid this topic — manipulating date objects is essential in our daily mission. Let’s see how to convert different dates to string correctly.

In the following paragraphs, I’ll use ISO 8601, an international standard covering the exchange of date and time-related data, as the string format. Date and time expressed according to ISO 8601 is:

2017-02-16T20:22:28+00:00 2017-02-16T20:22:28.000+00:00 

java.util.Date

Here’s an example to demonstrate how to convert a java.util.Date to ISO 8601 date string. This is a little bit tricky because we’re using the current time, which is the easiest use-case. For other cases, I believe using java.util.Calendar , java.util.GregorianCalendar would be a better solution. You can see the difference in the following paragraphs.

// Input Date date = new Date(System.currentTimeMillis()); // Conversion SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); sdf.setTimeZone(TimeZone.getTimeZone("CET")); String text = sdf.format(date); // Output // "2017-02-16T21:00:00.000+01:00"

java.util.Calendar

When using Calendar , we need to get an instance, then build a date object with it. Please be aware that setting the field of millisecond is necessary: lack of such line will lead to an erroneous value for millisecond. A non-zero value will be filled.

// Input Calendar calendar = Calendar.getInstance(); calendar.set(2017, Calendar.FEBRUARY, 16, 20, 22, 28); calendar.set(Calendar.MILLISECOND, 0); Date date = calendar.getTime(); // Conversion SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); sdf.setTimeZone(TimeZone.getTimeZone("CET")); String text = sdf.format(date); // Output // "2017-02-16T20:22:28.000+01:00"

java.util.GregorianCalendar

For gregorian calendar, we don’t need to set explicitly the millisecond datepart to 0, which is better than calendar. However, we still need to use java.util.Date as an intermediate to format the date.

// Input GregorianCalendar calendar; calendar = new GregorianCalendar(2017, Calendar.FEBRUARY, 16, 20, 22, 28); Date date = calendar.getTime(); // Conversion SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); sdf.setTimeZone(TimeZone.getTimeZone("CET")); String text = sdf.format(date); // Output // "2017-02-16T20:22:28.000+01:00"

java.time.ZonedDateTime

The package java.time , formerly Joda-Time, provides the most elegant solution among all the possibiliites here. It uses a builder to construct the date time with time zone step-by-step. Then this object accepts a formatter to format the date representation in string. Its month is a base-1 number, which means that January is equal to 1 instead of 0, so you can use the digit instead of the static Java field. Let’s see the code:

// Input ZonedDateTime d = LocalDate .of(2017, 2, 16) .atTime(20, 22, 28) .atZone(ZoneId.of("CET")); // Conversion String text = DateTimeFormatter.ISO_DATE_TIME.format(d); // Output // "2017-02-16T20:22:28+01:00[CET]"

Use customized date-time pattern:

// Conversion DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(d); // Output // "2017-02-16T20:22:28.000+01:00"

Patterns for formatting and parsing are available in the Javadoc of DateTimeFormatter (Java 8).

Conclusion

In this blog, we have seen different methods to create a date object and the associated way to cast that object into an ISO 8601 date representation. I demonstrated that common date object types can be used to convert into string, but most of them are hard to understand, and time-zone is not well supported. However, thanks to the implementation of JSR 310, Joda-Time is now migrated into Java SE 8 as package java.time .

By the way, if you need to use any of the code shown in this blog, feel free to use them and adapt into your own code. Happy coding and have a nive weekend!

This work is licensed under a Attribution 4.0 International license.

Источник

Читайте также:  Python raise not implemented
Оцените статью