下面列出了javax.servlet.http.PushBuilder#java.util.TimeZone 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) {
boolean pass = true;
TimeZone tz = TimeZone.getDefault();
try {
pass &= testRequiredLocales();
pass &= testRequiredEncodings();
} finally {
TimeZone.setDefault(tz);
}
if (!pass) {
System.out.println("\nSome tests failed.\n"
+ "If you installed the US-only J2RE for Windows, "
+ "failures are expected and OK.\n"
+ "If you installed the international J2RE, or any J2SDK, "
+ "or if this occurs on any platform other than Windows, "
+ "please file a bug report.\n"
+ "Unfortunately, this test cannot determine whether you "
+ "installed a US-only J2RE, an international J2RE, or "
+ "a J2SDK.\n");
throw new RuntimeException();
}
}
/**
* {@inheritDoc}
*/
public void appendTo(StringBuffer buffer, Calendar calendar) {
if (mTimeZoneForced) {
if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
buffer.append(mDaylight);
} else {
buffer.append(mStandard);
}
} else {
TimeZone timeZone = calendar.getTimeZone();
if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale));
} else {
buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale));
}
}
}
public RequestContext(ServerWebExchange exchange, Map<String, Object> model, MessageSource messageSource,
@Nullable RequestDataValueProcessor dataValueProcessor) {
Assert.notNull(exchange, "ServerWebExchange is required");
Assert.notNull(model, "Model is required");
Assert.notNull(messageSource, "MessageSource is required");
this.exchange = exchange;
this.model = model;
this.messageSource = messageSource;
LocaleContext localeContext = exchange.getLocaleContext();
Locale locale = localeContext.getLocale();
this.locale = (locale != null ? locale : Locale.getDefault());
TimeZone timeZone = (localeContext instanceof TimeZoneAwareLocaleContext ?
((TimeZoneAwareLocaleContext) localeContext).getTimeZone() : null);
this.timeZone = (timeZone != null ? timeZone : TimeZone.getDefault());
this.defaultHtmlEscape = null; // TODO
this.dataValueProcessor = dataValueProcessor;
}
@OnScheduled
public void OnScheduled(final ProcessContext context) {
// Configure jackson mapper before spawning onTriggers
final SimpleModule module = new SimpleModule()
.addSerializer(MacAddress.class, new MacAddressToStringSerializer());
mapper.registerModule(module);
mapper.setDateFormat(this.simpleDateFormat);
switch (context.getProperty(TIME_REPRESENTATION).getValue()) {
case LOCAL_TZ:
// set the mapper TZ to local TZ
mapper.setTimeZone(TimeZone.getDefault());
tzId = TimeZone.getDefault().getID();
break;
case UTC:
// set the mapper TZ to local TZ
mapper.setTimeZone(TimeZone.getTimeZone(UTC));
tzId = UTC;
break;
}
}
/**
* Returns true if this zone has the same raw GMT offset value and
* transition table as another zone info. If the specified
* TimeZone object is not a ZoneInfoOld instance, this method returns
* true if the specified TimeZone object has the same raw GMT
* offset value with no daylight saving time.
*
* @param other the ZoneInfoOld object to be compared with
* @return true if the given <code>TimeZone</code> has the same
* GMT offset and transition information; false, otherwise.
*/
public boolean hasSameRules(TimeZone other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof ZoneInfoOld)) {
if (getRawOffset() != other.getRawOffset()) {
return false;
}
// if both have the same raw offset and neither observes
// DST, they have the same rule.
if ((transitions == null)
&& (useDaylightTime() == false)
&& (other.useDaylightTime() == false)) {
return true;
}
return false;
}
if (getLastRawOffset() != ((ZoneInfoOld)other).getLastRawOffset()) {
return false;
}
return (checksum == ((ZoneInfoOld)other).checksum);
}
@Override
public ComReminder mapRow(ResultSet rs, int i) throws SQLException {
ComReminder reminder = new ComReminderImpl();
reminder.setId(rs.getInt("reminder_id"));
reminder.setCompanyId(rs.getInt("company_id"));
reminder.setRecipientEmail(rs.getString("email"));
reminder.setSenderName(getSenderName(rs.getString("sender_name"), rs.getString("sender_company_name")));
reminder.setMessage(rs.getString("message"));
reminder.setSent(rs.getInt("notified") != 0);
reminder.setLang(StringUtils.defaultIfEmpty(rs.getString("lang"), DEFAULT_LANGUAGE));
ReminderType reminderType = ReminderType.fromId(rs.getInt("type"));
// No content generation available for unknown or corrupted reminders.
if (reminderType != null) {
String workflowName = rs.getString("title");
// Recipient timezone (if available) or sender timezone (otherwise).
ZoneId zoneId = TimeZone.getTimeZone(rs.getString("timezone")).toZoneId();
LocalDateTime startDate = DateUtilities.toLocalDateTime(rs.getTimestamp("workflow_start_date"), zoneId);
LocalDateTime stopDate = DateUtilities.toLocalDateTime(rs.getTimestamp("workflow_stop_date"), zoneId);
generateContent(reminder, reminderType, workflowName, startDate, stopDate);
}
return reminder;
}
public String[][] getZoneStrings() {
synchronized (this) {
if (zoneStrings == null) {
String ids[] = TimeZone.getAvailableIDs();
String newZoneStrings[][] = new String[ids.length][5];
for (int i = 0; i < ids.length; i++) {
newZoneStrings[i][ZONE_ID] = ids[i]; // - time zone ID
String key = ids[i].toUpperCase();
newZoneStrings[i][ZONE_LONGNAME] = getLocalizedValue(L10N_ZONE_LONGNAME + key, ids[i]);
newZoneStrings[i][ZONE_SHORTNAME] = getLocalizedValue(L10N_ZONE_SHORTNAME + key, ids[i]);
newZoneStrings[i][ZONE_LONGNAME_DST] = getLocalizedValue(L10N_ZONE_LONGNAME_DST + key, ids[i]);
newZoneStrings[i][ZONE_SHORTNAME_DST] = getLocalizedValue(L10N_ZONE_SHORTNAME_DST + key, ids[i]);
}
zoneStrings = newZoneStrings;
}
}
return zoneStrings;
}
/**
* Some checks for the getFirstMillisecond(TimeZone) method.
*/
public void testGetFirstMillisecondWithCalendar() {
Minute m = new Minute(40, 2, 15, 4, 2000);
GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt"));
assertEquals(955766400000L, m.getFirstMillisecond(calendar));
// try null calendar
boolean pass = false;
try {
m.getFirstMillisecond((Calendar) null);
}
catch (NullPointerException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the getFirstMillisecond(TimeZone) method.
*/
@Test
public void testGetFirstMillisecondWithTimeZone() {
Minute m = new Minute(59, 15, 1, 4, 1950);
TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
assertEquals(-623289660000L, m.getFirstMillisecond(zone));
// try null calendar
boolean pass = false;
try {
m.getFirstMillisecond((TimeZone) null);
}
catch (NullPointerException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Gets the default time zone
* @return US Eastern Time Zone
*/
public static RhnTimeZone getDefaultTimeZone() {
RhnTimeZone sysDefault = getTimeZone(TimeZone.getDefault().getID());
if (sysDefault != null) {
return sysDefault;
}
Session session = HibernateFactory.getSession();
List<RhnTimeZone> allTimeZones =
session.getNamedQuery("RhnTimeZone.loadAll").list();
for (RhnTimeZone tz : allTimeZones) {
if (TimeZone.getDefault().getRawOffset() == TimeZone.getTimeZone(
tz.getOlsonName()).getRawOffset()) {
return tz;
}
}
// This should not happen unless the timezone table is incomplete
return getTimeZone("America/New_York");
}
/**
* Some checks for the getLastMillisecond(TimeZone) method.
*/
public void testGetLastMillisecondWithCalendar() {
Day d = new Day(4, 5, 2001);
Calendar calendar = Calendar.getInstance(
TimeZone.getTimeZone("Europe/London"), Locale.UK);
assertEquals(989017199999L, d.getLastMillisecond(calendar));
// try null calendar
boolean pass = false;
try {
d.getLastMillisecond((Calendar) null);
}
catch (NullPointerException e) {
pass = true;
}
assertTrue(pass);
}
@Test
public void testTimeStampUtc() throws SQLException {
TimeZone.setDefault(parisTimeZone);
try (Connection connection = setConnection("&serverTimezone=UTC&useServerPrepStmts=true")) {
setSessionTimeZone(connection, "+00:00");
// timestamp timezone to parisTimeZone like server
Timestamp currentTimeParis = new Timestamp(System.currentTimeMillis());
PreparedStatement st = connection.prepareStatement("SELECT ?");
st.setTimestamp(1, currentTimeParis);
ResultSet rs = st.executeQuery();
assertTrue(rs.next());
Timestamp t1 = rs.getTimestamp(1);
assertEquals(t1, currentTimeParis);
}
}
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
//SpringApplication.run(MoonApplication.class, args);
new SpringApplicationBuilder(MoonApplication.class)
.properties("spring.config.location:classpath:/apps/, classpath:/apis/, classpath:/")
.build().run(args);
}
public String getCurTime() {
String fromTimeZone = "GMT+8";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
format.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
String chinaDate = format.format(date);
return chinaDate;
}
@Test
public void preprocesTest()
{
final GroovyEngine engine = new GroovyEngine(Locale.GERMAN, TimeZone.getTimeZone("UTC"));
assertNull(engine.preprocessGroovyXml(null));
assertEquals("", engine.preprocessGroovyXml(""));
assertEquals("<% if (value != null) { %>", engine.preprocessGroovyXml("<groovy>if (value != null) {</groovy>"));
assertEquals("<%= value %>", engine.preprocessGroovyXml("<groovy-out>value</groovy-out>"));
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(PARIS);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
public PlaceLocation(String code, GeoLocation geoLocation, String primaryCity, String state, String county,
TimeZone timeZone)
{
this.code = code;
this.geoLocation = geoLocation;
this.geoPrecision = Place.GEOPRECISION_ZIP5;
this.primaryCity = primaryCity;
this.state = state;
this.county = county;
this.timeZone = timeZone;
}
private Long toTimestamp(ByteFragment value, TimeZone timeZone) {
if (value.isNull() || value.asString().equals("0000-00-00 00:00:00")) {
return null;
}
try {
dateTimeFormat.setTimeZone(timeZone);
return dateTimeFormat.parse(value.asString()).getTime();
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
String getViewTitle() {
return "DateTime.getXXX() Method Calculations"
+ " : "
+ TimeZone.getDefault().getDisplayName()
+ " : "
+ " Record Count "
+ currFile.getLoadedFileSize();
}
private static void assertSameRules(final String label,
final TimeZone expected,
final TimeZone actual) {
if (null == expected && null == actual) return;
assertNotNull(label + ": expected is null", expected);
assertNotNull(label + ": actual is null", actual);
final boolean same = expected.hasSameRules(actual);
assertTrue(label + ": " + expected.toString() + " [[NOT SAME RULES]] " +
actual.toString(),
same);
}
private String getLocalizedDate(int year, int month, int day) {
// we use the default Locale/TZ since LuceneTestCase randomizes it
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
Calendar calendar = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
calendar.clear();
calendar.set(year, month, day);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return df.format(calendar.getTime());
}
@Override
public Time getTimeFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs)
throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null) {
return null;
}
return getTimeFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs);
}
private DesignTimeDataFactoryContext createDataFactoryContext() {
return new DesignTimeDataFactoryContext(
ClassicEngineBoot.getInstance().getGlobalConfig(),
new ResourceManager(), null,
new DefaultResourceBundleFactory( Locale.getDefault(), TimeZone.getTimeZone( "UTC" ))
);
}
/**
* The fuller constructor
*
* @param pattern the format pattern
* @param timeZone the time zone
* @param locale the locale
*/
public TmfTimestampFormat(@NonNull String pattern, TimeZone timeZone, Locale locale) {
super("", locale); //$NON-NLS-1$
fLocale = locale;
setTimeZone(timeZone);
setCalendar(Calendar.getInstance(timeZone, locale));
fPattern = pattern;
applyPattern(pattern);
}
/**
* Constructs a Quarter, based on a date/time and time zone.
*
* @param time the date/time.
* @param zone the zone (<code>null</code> not permitted).
*/
public Quarter(Date time, TimeZone zone) {
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(time);
int month = calendar.get(Calendar.MONTH) + 1;
this.quarter = (byte) SerialDate.monthCodeToQuarter(month);
this.year = (short) calendar.get(Calendar.YEAR);
peg(calendar);
}
/**
* Gets a time zone instance for a JDK TimeZone.
* <p>
* DateTimeZone only accepts a subset of the IDs from TimeZone. The
* excluded IDs are the short three letter form (except UTC). This
* method will attempt to convert between time zones created using the
* short IDs and the full version.
* <p>
* This method is not designed to parse time zones with rules created by
* applications using <code>SimpleTimeZone</code> directly.
*
* @param zone the zone to convert, null means default
* @return the DateTimeZone object for the zone
* @throws IllegalArgumentException if the zone is not recognised
*/
public static DateTimeZone forTimeZone(TimeZone zone) {
if (zone == null) {
return getDefault();
}
final String id = zone.getID();
if (id.equals("UTC")) {
return DateTimeZone.UTC;
}
// Convert from old alias before consulting provider since they may differ.
DateTimeZone dtz = null;
String convId = getConvertedId(id);
if (convId != null) {
dtz = cProvider.getZone(convId);
}
if (dtz == null) {
dtz = cProvider.getZone(id);
}
if (dtz != null) {
return dtz;
}
// Support GMT+/-hh:mm formats
if (convId == null) {
convId = zone.getID();
if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) {
convId = convId.substring(3);
int offset = parseOffset(convId);
if (offset == 0L) {
return DateTimeZone.UTC;
} else {
convId = printOffset(offset);
return fixedOffsetZone(convId, offset);
}
}
}
throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised");
}
public void testTimestampOutMap() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow"));
cal.clear();
cal.set(2008, 8, 23, 14, 35, 4);
Date date = cal.getTime();
Map<String, Date> map = new HashMap<String, Date>();
map.put("canonical", date);
String output = dump(map);
assertEquals("{canonical: !!timestamp '2008-09-23T10:35:04Z'}\n", output);
}
/**
* Calculate the AWS CodeCommit password for the provided URI and AWS secret key. This
* uses the algorithm published by AWS at
* https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
* @param uri the codecommit repository uri
* @param awsSecretKey the aws secret key
* @return the password to use in the git request
*/
protected static String calculateCodeCommitPassword(URIish uri, String awsSecretKey) {
String[] split = uri.getHost().split("\\.");
if (split.length < 4) {
throw new CredentialException("Cannot detect AWS region from URI", null);
}
String region = split[1];
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStamp = dateFormat.format(now);
String shortDateStamp = dateStamp.substring(0, 8);
String codeCommitPassword;
try {
StringBuilder stringToSign = new StringBuilder();
stringToSign.append("AWS4-HMAC-SHA256\n").append(dateStamp).append("\n")
.append(shortDateStamp).append("/").append(region)
.append("/codecommit/aws4_request\n")
.append(bytesToHexString(canonicalRequestDigest(uri)));
byte[] signedRequest = sign(awsSecretKey, shortDateStamp, region,
stringToSign.toString());
codeCommitPassword = dateStamp + "Z" + bytesToHexString(signedRequest);
}
catch (Exception e) {
throw new CredentialException("Error calculating AWS CodeCommit password", e);
}
return codeCommitPassword;
}
public void testTimezone() {
DumperOptions options = new DumperOptions();
options.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
Yaml yaml = new Yaml(options);
Date date = new Date();
String output = yaml.dump(date);
// System.out.println(output);
assertTrue(output, output.trim().endsWith("+1:00"));
Date parsed = (Date) yaml.load(output);
assertEquals(date, parsed);
}
protected String toRangeDateString(Date date, String format) {
if (format.contains("epoch_millis")) {
return Long.toString(date.getTime());
} else if (format.contains("date_optional_time")) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(date);
} else {
return Long.toString(date.getTime());
}
}