Java Date conversion
Today we have some useful code for you – the Java Date Conversion example. SimpleDateFormat
and it’s parse
and format
methods are used to convert String
to Date
(parse method) and Date
to String
(format method). Here are the examples.
Java Date Conversion – String to Date
This example converts String
object to Date
object. Two String
dates are created here – one is the English language date and other one is the Polish language date. Each String
is converted to a Date
object using SimpleDateFormat.parse
method, and then the resulting objects are compared.
try { // EXAMPLE 1: from String to Date System.out.println("EXAMPLE 1: from String to Date"+"\n"); // English language date String stringDateEN = "10:00 April 1, 2013"; String stringDatePL = "10:00 Kwiecień 1, 2013"; // Change this to your language and see how it works :) // Parse the English date Date dateEN = new SimpleDateFormat("HH:mm MMMM d, yyyy", Locale.ENGLISH).parse(stringDateEN); System.out.println("\t"+"dateEN: " + dateEN); // Parse your date, system default (in our case PL - polish) - no Locale is provided Date datePL = new SimpleDateFormat("HH:mm MMMM d, yyyy").parse(stringDatePL); System.out.println("\t"+"datePL: " + datePL); // Are they the same? System.out.println("\t"+"dateEN == datePL " + dateEN.equals(datePL)); } catch (ParseException e) { e.printStackTrace(); }
output:
EXAMPLE 1: from String to Date dateEN: Mon Apr 01 10:00:00 CEST 2013 datePL: Mon Apr 01 10:00:00 CEST 2013 dateEN == datePL true
Java Date Conversion – Date to String
To convert from Date
to String
use SimpleDateFormat.format
method. In our example we display default formatted current date and then we format it match HH:mm:ss MMMM d, yyyy
pattern.
try { // EXAMPLE 2: from Date to String System.out.println("EXAMPLE 2: from Date to String"+"\n"); // Now! Date currentDate = new Date(); System.out.println("\t"+"currentDate: " + currentDate); System.out.println("\t"+"currentDate: " + new SimpleDateFormat("HH:mm:ss MMMM d, yyyy").format(currentDate)); } catch (ParseException e) { e.printStackTrace(); }
output:
EXAMPLE 2: from Date to String currentDate: Thu Mar 28 18:07:58 CET 2013 currentDate: 18:07:58 marzec 28, 2013
Download this sample code here.
This code is available on our GitHub repository as well.
Leave a Reply
Want to join the discussion?Feel free to contribute!