Set time to 00:00:00

前端 未结 12 2150
时光说笑
时光说笑 2020-11-29 20:04

I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.

This is my code :

/**
     * Resets milliseconds, se         


        
12条回答
  •  [愿得一人]
    2020-11-29 20:45

    You would better to primarily set time zone to the DateFormat component like this:

    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    

    Then you can get "00:00:00" time by passing 0 milliseconds to formatter:

    String time = dateFormat.format(0);
    

    or you can create Date object:

    Date date = new Date(0); // also pass milliseconds
    String time = dateFormat.foramt(date);
    

    or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:

    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
    calendar.set(Calendar.HOUR_OF_DAY, 5);
    calendar.set(Calendar.MINUTE, 37);
    calendar.set(Calendar.SECOND, 27);
    
    dateFormat.format(calendar.getTime());
    

提交回复
热议问题