Java - Date as long value: how does TimeZone relat

2019-06-22 05:41发布

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?

4条回答
Rolldiameter
2楼-- · 2019-06-22 06:06

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-06-22 06:07

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-06-22 06:10

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

查看更多
爷、活的狠高调
5楼-- · 2019-06-22 06:15

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));
查看更多
登录 后发表回答