Search code examples
javadatetimestampsimpledateformattime-format

Convert system time as string to Timestamp


I’m trying to get the time of my computer using Java and format it in specific order using SimpleDateFormat object but it won't format; please help.

This is my code :

java.util.Date parsedDate = null;      
try {   
    DateFormat dateFormat = new SimpleDateFormat("HH:mm");  
    parsedDate = dateFormat.parse(dateFormat.format(new java.util.Date()));
}catch(ParseException e){
}  
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());

Solution

  • tl;dr

    LocalTime
        .now( ZoneId.of( "Pacific/Auckland" ) ) 
        .toString() 
    

    java.time

    You are using troublesome troublesome old legacy classes that are now supplanted by the modern java.time classes. Avoid the old classes entirely.

    Get the current moment in UTC with a resolution of up to nanoseconds.

    Instant instant = Instant.now() ;
    

    To see that same moment through a particular region’s wall-clock time, apply a time zone.

    ZoneId z = ZoneId.of( "America/Montreal" ) ;
    ZonedDateTime zdt = instant.atone( z ) ;
    

    To work with only a time-of-day without a date and without a time zone, extract a LocalTime object.

    LocalTime lt = zdt.toLocalTime() ;
    

    If by "format to specific order" you meant sorting… These objects know how to sort. No need for a string just for sorting.

    List<LocalTime> times = new ArrayList<>() ;
    times.add( lt ) ;
    …
    Collections.sort( times ) ;
    

    Generate a String for display to user. The java.time classes use standard ISO 8601 formats by default for generating/parsing strings.

    String output = lt.toString() ;
    

    For other formats, use DateTimeFormatter.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "HH:mm" ) ;
    String output = lt.format( f ) ;
    

    All of this has been handled many times on Stack Overflow. Search for more info and discussion.