Search code examples
javatimetimestamplong-integermilliseconds

Java: Convert long time of day to timestamp


I have a long value that represents the time of day in milliseconds since midnight that day. i.e. 00:00:01 would be 1000.

I want to convert this to a long timestamp since the epoch - using the current System's day, month, year. What's the best way to do this?


Solution

  •     final Calendar instance = Calendar.getInstance();
        instance.set(Calendar.HOUR, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        instance.set(Calendar.MILLISECOND, 0);
        long result = instance.getTimeInMillis() + yourTime;
    

    Also note that Calendar#getInstance does the following:

    Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());

    The resulting time will change according to the default set TimeZone (and yes it can change !). See this post: java Timezone setDefault effects