Java - Date as long value: how does TimeZone relat

2019-06-22 05:21发布

问题:

Could someone please explain in detail the following:

I have a long value which represents a date.

  1. What will be the timezone associated with the long value?

  2. How to convert the long value to a date with proper time zone?

  3. Is there is way to identify the timezone associated with the long date value?

回答1:

The long is milliseconds since Jan 1970, GMT. So, to that respect, it is GMT.



回答2:

The long value which represents the java.util.Date is the number of milliseconds elapsed from epoch. (Jan 1, 1970)

/**
 * Allocates a <code>Date</code> object and initializes it to 
 * represent the specified number of milliseconds since the 
 * standard base time known as "the epoch", namely January 1, 
 * 1970, 00:00:00 GMT. 
 *
 * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
 * @see     java.lang.System#currentTimeMillis()
 */
public Date(long date) {
    fastTime = date;
}
  • What will be the timezone associated with the long value?
    Can you attach a unit to a long value.? No.
    This is akin to saying given an int 2 what does it represent? . It could be 2 miles or 2 pounds.

  • How to convert the long value to a date with proper time zone?
    You can't because of above.

  • Is there is way to identify the timezone associated with the long date value?
    Nope.



回答3:

A Date (either as a long or a java.util.Date) represents a moment in time.

There is no TimeZone involved unless you're dealing with a Calendar.

You can create a Calendar for a given TimeZone and Locale like this:

long rightNow = System.currentTimeMillis();
Locale exampleLocale = Locale.GERMANY;
TimeZone zone = TimeZone.getTimeZone("EST");

Calendar theCalendar = Calendar.getInstance(zone, exampleLocale);
theCaledar.setTime(new Date(rightNow));


回答4:

When time is in long format, TimeZone won't be associated with it.

You need to use either SimpleDateFormat (or) Calendar API to apply Timezone for long value.