fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.text.SimpleDateFormat ;
  8.  
  9. import java.time.* ;
  10. import java.time.temporal.* ;
  11. import java.time.format.* ;
  12.  
  13. /* Name of the class has to be "Main" only if the class is public. */
  14. class Ideone
  15. {
  16. public static void main (String[] args) throws java.lang.Exception
  17. {
  18. String input = "2017/08/01 15:18:01" ;
  19.  
  20. // Old outmoded way using troublesome legacy classes.
  21. SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  22. Date date = format.parse( input ) ;
  23. Calendar cal = Calendar.getInstance() ;
  24. cal.setTime( date ) ;
  25. System.out.println( "date.toString(): " + date ) ;
  26.  
  27. // New modern way in Java 8 and later.
  28. DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/MM/dd HH:mm:ss" , Locale.US ) ;
  29. LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
  30. // If we assume this date-time was meant to be UTC.
  31. OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
  32. System.out.println( "odt.toString(): " + odt ) ;
  33.  
  34. }
  35. }
Success #stdin #stdout 0.42s 2841600KB
stdin
Standard input is empty
stdout
date.toString(): Tue Aug 01 15:18:01 GMT 2017
odt.toString(): 2017-08-01T15:18:01Z