- Data Type Conversions in Java
- String to int
- String to long
- String to float
- String to double
- NumberFormatException
- String to boolean
- String to Date
- Date to String
- Date to ISO 8601 String
- Conclusion
- Convert Date to String in Java
- Convert Date to String Using SimpleDateFormat in Java
- Convert Date to String Using DateFormatUtils Class in Java
- Convert Date to String Using DateTimeFormatter in Java
- Convert Date to String With the Time Zone in Java
- Convert Date to String With String Class in Java
- Related Article — Java String
- Related Article — Java DateTime
- Convert date value to string in java
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
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 String in Java
- Convert Date to String Using SimpleDateFormat in Java
- Convert Date to String Using DateFormatUtils Class in Java
- Convert Date to String Using DateTimeFormatter in Java
- Convert Date to String With the Time Zone in Java
- Convert Date to String With String Class in Java
This tutorial introduces how to convert java.util.Date to String in Java and lists some example codes to understand it.
Java has several classes and methods that help convert Date to String like using SimpleDateFormat , DateFormatUtils , and DateTimeFormatter class.
Convert Date to String Using SimpleDateFormat in Java
Here, We use format() method of SimpleDateFormat class to get String from the util.Date object in Java.
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleTesting public static void main(String[] args) throws ParseException DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); Date date = new Date(); String dateToStr = dateFormat.format(date); System.out.println("Date is "+ dateToStr); > >
Convert Date to String Using DateFormatUtils Class in Java
If you are using the Apache library then use format() method of DateFormateUtils class. It returns a string after converting java.util.Date to string in Java.
import java.text.ParseException; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; public class SimpleTesting public static void main(String[] args) throws ParseException Date date = new Date(); String dateToStr = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:SS"); System.out.println("Date is "+ dateToStr); > >
Convert Date to String Using DateTimeFormatter in Java
Here, we use the format() method that takes the ofPattern() method as an argument and returns a string representation of a date. See the example below.
import java.text.ParseException; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; public class SimpleTesting public static void main(String[] args) throws ParseException Date date = new Date(); String dateToStr = date.toInstant() .atOffset(ZoneOffset.UTC) .format( DateTimeFormatter.ofPattern("dd-MM-yyyy")); System.out.println("Date is "+ dateToStr); > >
Convert Date to String With the Time Zone in Java
Here, we use format() method of the DateTimeFormatter class to get string after conversion from java.util.date . We get time zone along with date because we specified the date-time format in the ofPattern() method.
import java.text.ParseException; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; public class SimpleTesting public static void main(String[] args) throws ParseException Date date = new Date(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z") .withZone(ZoneId.systemDefault()); String dateToStr = format.format(date.toInstant()); System.out.println("Date is "+ dateToStr); > >
Date is 2020-09-21 09:10:23:991 +0530
Convert Date to String With String Class in Java
This is one of the simplest solutions to get a String of java.util.date object. Here, we use the format() method of the String class that formats the date based on the specified format. See the example below.
import java.text.ParseException; import java.util.Date; public class SimpleTesting public static void main(String[] args) throws ParseException Date date = new Date(); String dateToStr = String.format("%1$tY-%1$tm-%1$td", date); System.out.println("Date is "+ dateToStr); > >
Related Article — Java String
Related Article — Java DateTime
Convert date value to string in java
Let’s see the full example to convert date and time into String in java using format() method of java.text.SimpleDateFormat class.
Date Format with MM/dd/yyyy : 04/13/2015 Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26 Date Format with dd MMMM yyyy : 13 April 2015 Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter