java.util.TimeZone类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(138)

本文整理了Java中java.util.TimeZone类的一些代码示例,展示了TimeZone类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。TimeZone类的具体详情如下:
包路径:java.util.TimeZone
类名称:TimeZone

TimeZone介绍

[英]TimeZone represents a time zone offset, and also figures out daylight savings.

Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time.

You can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a U.S. Pacific Time TimeZone object with:

TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");

You can use the getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a TimeZone. If the time zone you want is not represented by one of the supported IDs, then a custom time zone ID can be specified to produce a TimeZone. The syntax of a custom time zone ID is:

CustomID: 
GMT Sign Hours : Minutes 
GMT Sign Hours Minutes 
GMT Sign Hours 
Sign: one of 
+ - 
Hours: 
Digit 
Digit Digit 
Minutes: 
Digit Digit 
Digit: one of 
0 1 2 3 4 5 6 7 8 9

Hours must be between 0 to 23 and Minutes must be between 00 to 59. For example, "GMT+10" and "GMT+0010" mean ten hours and ten minutes ahead of GMT, respectively.

The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard. No daylight saving time transition schedule can be specified with a custom time zone ID. If the specified string doesn't match the syntax, "GMT" is used.

When creating a TimeZone, the specified custom time zone ID is normalized in the following syntax:

NormalizedCustomID: 
GMT Sign TwoDigitHours : Minutes 
Sign: one of 
+ - 
TwoDigitHours: 
Digit Digit 
Minutes: 
Digit Digit 
Digit: one of 
0 1 2 3 4 5 6 7 8 9

For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00".

Three-letter time zone IDs

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
[中]TimeZone表示时区偏移量,还表示夏令时。
通常,使用getDefault可以获得TimeZone,这会根据程序运行的时区创建TimeZone。例如,对于在日本运行的程序,getDefault基于日本标准时间创建一个TimeZone对象。
您还可以使用getTimeZone和时区ID获得TimeZone。例如,美国太平洋时区的时区ID为“America/Los_Angeles”。因此,您可以通过以下方式获得美国太平洋时间TimeZone对象:

TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");

您可以使用getAvailableIDs方法遍历所有受支持的时区ID。然后,您可以选择一个受支持的ID以获得TimeZone。如果所需的时区未由支持的ID之一表示,则可以指定自定义时区ID以生成时区。自定义时区ID的语法是:

CustomID: 
GMT Sign Hours : Minutes 
GMT Sign Hours Minutes 
GMT Sign Hours 
Sign: one of 
+ - 
Hours: 
Digit 
Digit Digit 
Minutes: 
Digit Digit 
Digit: one of 
0 1 2 3 4 5 6 7 8 9

小时必须介于0到23之间,分钟必须介于00到59之间。例如,“GMT+10”和“GMT+0010”分别表示比GMT早10小时和10分钟。
格式与地区无关,数字必须取自Unicode标准的基本拉丁语块。无法使用自定义时区ID指定夏令时转换计划。如果指定的字符串与语法不匹配,则使用"GMT"
创建TimeZone时,指定的自定义时区ID将按以下语法规范化:

NormalizedCustomID: 
GMT Sign TwoDigitHours : Minutes 
Sign: one of 
+ - 
TwoDigitHours: 
Digit Digit 
Minutes: 
Digit Digit 
Digit: one of 
0 1 2 3 4 5 6 7 8 9

例如,时区。getTimeZone(“GMT-8”)。getID()返回“GMT-08:00”。
#####三个字母的时区ID
与JDK 1.1兼容。x、 还支持其他一些三字母时区ID(如“PST”、“CTT”、“AST”)。但是,由于同一缩写通常用于多个时区(例如,“CST”可以是美国的“中央标准时间”和“中国标准时间”),因此不推荐使用它们,Java平台只能识别其中一个时区。

代码示例

代码示例来源:origin: jenkinsci/jenkins

private static String clientDateString() {
  TimeZone tz = TimeZone.getTimeZone("UTC");
  DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
  df.setTimeZone(tz); // strip timezone
  return df.format(new Date());
}

代码示例来源:origin: stackoverflow.com

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
    new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

代码示例来源:origin: apache/flink

private Timestamp convertToTimestamp(Object object) {
  final long millis;
  if (object instanceof Long) {
    millis = (Long) object;
  } else {
    // use 'provided' Joda time
    final DateTime value = (DateTime) object;
    millis = value.toDate().getTime();
  }
  return new Timestamp(millis - LOCAL_TZ.getOffset(millis));
}

代码示例来源:origin: stackoverflow.com

import java.util.TimeZone;

public class Test {
  public static void main(String[] args) throws Exception {
    long startOf1900Utc = -2208988800000L;
    for (String id : TimeZone.getAvailableIDs()) {
      TimeZone zone = TimeZone.getTimeZone(id);
      if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
        System.out.println(id);
      }
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Parse the given {@code timeZoneString} value into a {@link TimeZone}.
 * @param timeZoneString the time zone {@code String}, following {@link TimeZone#getTimeZone(String)}
 * but throwing {@link IllegalArgumentException} in case of an invalid time zone specification
 * @return a corresponding {@link TimeZone} instance
 * @throws IllegalArgumentException in case of an invalid time zone specification
 */
public static TimeZone parseTimeZoneString(String timeZoneString) {
  TimeZone timeZone = TimeZone.getTimeZone(timeZoneString);
  if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) {
    // We don't want that GMT fallback...
    throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'");
  }
  return timeZone;
}

代码示例来源:origin: prestodb/presto

@Config("hive.time-zone")
public HiveClientConfig setTimeZone(String id)
{
  this.timeZone = (id != null) ? id : TimeZone.getDefault().getID();
  return this;
}

代码示例来源:origin: alibaba/canal

public final String formatUTCTZ(Date date) {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
  return sdf.format(date);
}

代码示例来源:origin: org.testng/testng

static String timeAsGmt() {
 SimpleDateFormat sdf = new SimpleDateFormat();
 sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
 sdf.applyPattern("dd MMM yyyy HH:mm:ss z");
 return sdf.format(Calendar.getInstance().getTime());
}

代码示例来源:origin: stackoverflow.com

String getServerTime() {
  Calendar calendar = Calendar.getInstance();
  SimpleDateFormat dateFormat = new SimpleDateFormat(
    "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
  dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  return dateFormat.format(calendar.getTime());
}

代码示例来源:origin: stackoverflow.com

Calendar c = Calendar.getInstance();
c.setTime(new Date(yourmilliseconds));
c.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(c.getTime()));

代码示例来源:origin: stackoverflow.com

UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));

代码示例来源:origin: knowm/XChange

public static Long toEpoch(Date dateTime, String timeZone) {
 // Epoch of midnight in local time zone
 Calendar timeOffset = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
 timeOffset.set(Calendar.MILLISECOND, 0);
 timeOffset.set(Calendar.SECOND, 0);
 timeOffset.set(Calendar.MINUTE, 0);
 timeOffset.set(Calendar.HOUR_OF_DAY, 0);
 long midnightOffSet = timeOffset.getTime().getTime();
 long localTimestamp = dateTime.getTime();
 return timeOffset == null ? null : midnightOffSet + localTimestamp;
}

代码示例来源:origin: AsyncHttpClient/async-http-client

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response    HTTP response
 * @param fileToCache file to extract content type
 */
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
 SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
 dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
 // Date header
 Calendar time = new GregorianCalendar();
 response.headers().set(DATE, dateFormatter.format(time.getTime()));
 // Add cache headers
 time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
 response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
 response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
 response.headers().set(
     LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}

代码示例来源:origin: blynkkk/blynk-server

/**
 * Sets the Date header for the HTTP response
 *
 * @param response
 *            HTTP response
 */
private static void setDateHeader(FullHttpResponse response) {
  SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
  dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
  Calendar time = new GregorianCalendar();
  response.headers().set(DATE, dateFormatter.format(time.getTime()));
}

代码示例来源:origin: knowm/XChange

@Override
 public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  final String dateTimeInUnixFormat = p.getText();
  try {
   Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
   calendar.setTimeInMillis(Long.parseLong(dateTimeInUnixFormat + "000"));
   return calendar.getTime();
  } catch (Exception e) {
   return new Date(0);
  }
 }
}

代码示例来源:origin: stackoverflow.com

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");

代码示例来源:origin: stackoverflow.com

Calendar c = Calendar.getInstance();
 System.out.println("current: "+c.getTime());
 TimeZone z = c.getTimeZone();
 int offset = z.getRawOffset();
 if(z.inDaylightTime(new Date())){
   offset = offset + z.getDSTSavings();
 }
 int offsetHrs = offset / 1000 / 60 / 60;
 int offsetMins = offset / 1000 / 60 % 60;
 System.out.println("offset: " + offsetHrs);
 System.out.println("offset: " + offsetMins);
 c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
 c.add(Calendar.MINUTE, (-offsetMins));
 System.out.println("GMT Time: "+c.getTime());

代码示例来源:origin: square/moshi

private Date newDate(int year, int month, int day, int hour, int offset) {
  Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
  calendar.set(year, month - 1, day, hour, 0, 0);
  calendar.set(Calendar.MILLISECOND, 0);
  return new Date(calendar.getTimeInMillis() - TimeUnit.HOURS.toMillis(offset));
 }
}

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testFormat() {
  final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone());
  c.set(2005, Calendar.JANUARY, 1, 12, 0, 0);
  c.setTimeZone(TimeZone.getDefault());
  final StringBuilder buffer = new StringBuilder ();
  final int year = c.get(Calendar.YEAR);
  final int month = c.get(Calendar.MONTH) + 1;
  final int day = c.get(Calendar.DAY_OF_MONTH);
  final int hour = c.get(Calendar.HOUR_OF_DAY);
  buffer.append (year);
  buffer.append(month);
  buffer.append(day);
  buffer.append(hour);
  assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH"));
  assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH"));
  assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH", Locale.US));
  assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH", Locale.US));
}

代码示例来源:origin: stackoverflow.com

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

相关文章