0

I am working on a piece of work where I need to get year, month, day from a String in Java. The string is like that: 20170119T163048

Where 2017 is year, 01 is month, 19 is day, 16:30:48 is time.

I implemented code like this below:

public void convertStringToDate (String string) {
    String dateInString = "";   
    SimpleDateFormat formatter = new SimpleDateFormat();
    Date date = formatter.parse("20170119T163048");
    System.out.println(date);
}

But seems like it does not work. Looking around and I actually found quite lots of similar answer but none of them really work for me so...

djm.im
  • 3,295
  • 4
  • 30
  • 45
Long Dao
  • 1,341
  • 4
  • 15
  • 33
  • 6
    Try the format along the lines of `yyyyMMdd'T'HHmmSS` - or better yet, make use of the newer Date/Time API - for [example](http://stackoverflow.com/questions/18119665/geting-duration-of-2-times/18120233#18120233) – MadProgrammer Jan 20 '17 at 02:02
  • yeah it works for me so far. Thanks. – Long Dao Jan 20 '17 at 02:08
  • Abd the more general dupe: [Java string to date conversion](//stackoverflow.com/q/4216745) – Tom Jan 20 '17 at 02:09
  • `LocalDateTime.parse( "20170119T163048" , DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ).getYear()` & `.getMonthValue()` & `.getDayOfMonth()`. – Basil Bourque Feb 16 '18 at 21:16

1 Answers1

5

You Shall always refer to the documentation.Simple Date Format Documentation

public static void main(String[] args) throws Exception{
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
    Date date = formatter.parse("20170119T163048");
    System.out.println(date.toString());
}
djm.im
  • 3,295
  • 4
  • 30
  • 45
Srikanth Balaji
  • 2,638
  • 4
  • 18
  • 31
  • Oh it works, thanks. But may I know what is the 'T'? I think it was the main part that makes me feel confused. – Long Dao Jan 20 '17 at 02:07
  • 'T' denotes time in your time format string. Always worth going through the Official documentation - https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Srikanth Balaji Jan 20 '17 at 02:10
  • Actually, in the context of the format 'T' means a literal, it expects to find 'T' at this point in the format. For the ISO format, 'T' is the time separator. The new Date/Time API have a number of ISO formats readily available ;) – MadProgrammer Jan 20 '17 at 02:17
  • wow a lot of upvotes for this answer – Scary Wombat Jan 20 '17 at 02:18
  • @ScaryWombat, yes, for a very straight forward question – Srikanth Balaji Jan 20 '17 at 02:20