Created
May 31, 2017 16:50
-
-
Save amihalik/ca451dfee90900130946a0e20d662f2e to your computer and use it in GitHub Desktop.
A "Pre Java 8" and Java 8 example of parsing a date/time string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.time.LocalDateTime; | |
import java.time.format.DateTimeFormatter; | |
import java.util.Calendar; | |
import java.util.Date; | |
import java.util.GregorianCalendar; | |
public class ParsingExample { | |
public static void main(String[] args) { | |
// Based off of: | |
// https://www.mkyong.com/java/how-to-convert-string-to-date-java/ | |
String dateInString = "2017-05-31T12:52:21.0000Z"; | |
// Pre Java 8 | |
System.out.println("Pre Java 8"); | |
try { | |
//Parse the String | |
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"); | |
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss"); | |
Date date = formatter.parse(dateInString); | |
System.out.println("Get the Month Day and Year Fields"); | |
Calendar calendar = new GregorianCalendar(); | |
calendar.setTime(date); | |
System.out.println("Month :: " + calendar.get(Calendar.MONTH)); | |
System.out.println("Day :: " + calendar.get(Calendar.DAY_OF_MONTH)); | |
System.out.println("Year :: " + calendar.get(Calendar.YEAR)); | |
System.out.println(); | |
System.out.println("Write the Date using a different format"); | |
SimpleDateFormat newformatter = new SimpleDateFormat("'Month' :: MMM, 'Day' :: dd, 'Year' :: yyyy"); | |
System.out.println(newformatter.format(date)); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
// Java 8 | |
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"); | |
//default, ISO_LOCAL_DATE | |
LocalDateTime localDate = LocalDateTime.parse(dateInString, formatter); | |
System.out.println(); | |
System.out.println("Get the Month Day and Year Fields"); | |
System.out.println("Month :: " + localDate.getMonth()); | |
System.out.println("Day :: " + localDate.getDayOfMonth()); | |
System.out.println("Year :: " + localDate.getYear()); | |
System.out.println(); | |
System.out.println("Write the Date using a different format"); | |
DateTimeFormatter newformatter = DateTimeFormatter.ofPattern("'Month' :: MMM, 'Day' :: dd, 'Year' :: yyyy"); | |
System.out.println(newformatter.format(localDate)); | |
System.out.println(localDate); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment