Java 类java.util.TimeZone 实例源码

项目:puremadrid    文件:ApiMedicion.java   
public ApiMedicion(Date measuredAt, String currentState, String avisoState, String avisoMaxToday, String escenarioToday, String escenarioTomorrow, String escenarioTomorrowManual, boolean isPureMadrid) {
    this.isPureMadrid = isPureMadrid;
    MIN_VALUE_PREAVISO = isPureMadrid ? 180 : 140; //180;
    MIN_VALUE_AVISO = isPureMadrid ? 200 : 180; //200;
    MIN_VALUE_ALERTA = isPureMadrid ? 400 : 300; //400;

    this.aviso = currentState;
    this.avisoState = avisoState;
    this.avisoMaxToday = avisoMaxToday;
    this.escenarioStateToday = escenarioToday;
    this.escenarioStateTomorrow = escenarioTomorrow;
    this.escenarioManualTomorrow = escenarioTomorrowManual;

    if (measuredAt == null){
        this.measuredAt = null;
    } else {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
        calendar.setTime(measuredAt);
        this.measuredAt = calendar;
    }
}
项目:andcouchbaseentity    文件:TaskActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Application application = (Application) getApplication();
    mDatabase = application.getDatabase();

    if (savedInstanceState != null)
        mListId = savedInstanceState.getString(INTENT_LIST_ID);
    else
        mListId = getIntent().getStringExtra(INTENT_LIST_ID);

    Query query = getQuery();
    mAdapter = new TaskAdapter(this, query.toLiveQuery());

    ListView listView = (ListView) findViewById(R.id.list);
    listView.setAdapter(mAdapter);
    setListHeader(listView);
    setListItemLongClick(listView);

    mDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
项目:TimeAndMoney    文件:JavaUtilCalendarQuirksTest.java   
@Test
public void testHourOfDay() {
    TimeZone gmt = TimeZone.getTimeZone("Universal");
    Calendar test = Calendar.getInstance(gmt);
    test.set(Calendar.YEAR, 1969);
    test.set(Calendar.MONTH, Calendar.JULY);
    test.set(Calendar.DATE, 20);
    test.set(Calendar.HOUR_OF_DAY, 3);

    assertEquals(1969, test.get(Calendar.YEAR));
    assertEquals(Calendar.JULY, test.get(Calendar.MONTH));
    assertEquals(20, test.get(Calendar.DATE));
    assertEquals(3, test.get(Calendar.HOUR));
    assertEquals(Calendar.AM, test.get(Calendar.AM_PM));
    assertEquals(3, test.get(Calendar.HOUR_OF_DAY));
}
项目:spring-boot-gae    文件:OffsetDateTimeStringTranslatorFactoryTest.java   
@Test
public void testLoad() throws Exception {
    new ExecuteAsTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC))
            .run(() -> assertThat(
                    load("2017-08-28T07:09:36.000000042Z")
                            .isEqual(OffsetDateTime.of(2017, 8, 28, 7, 9, 36, 42, ZoneOffset.UTC)),
                    is(true)
            ));
}
项目:fitnotifications    文件:YMDDateFormatter.java   
/**
 * Returns a version of this formatter customized to the provided time zone.
 */
public DateFormatter withTimeZone(TimeZone tz) {
  if (!tz.equals(timeZone)) {
    return new YMDDateFormatter(requestedFields, localeName, tz);
  }
  return this;
}
项目:ForeverLibrary    文件:MiscUtil.java   
public static long getDateTimeFromString(String strDate) {
    long nTimeNow = 0;

    if (strDate == null) {
        return 0;
    }

    try {
        SimpleDateFormat myFmt2 = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        myFmt2.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date dt = myFmt2.parse(strDate.trim());

        nTimeNow = dt.getTime();
    } catch (Exception ex) {
    }

    return nTimeNow;
}
项目:RLibrary    文件:TimeUtil.java   
public static String getBeijingNowTime(String format) {
    TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");

    Date date = new Date(currentTimeMillis());
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
    formatter.setTimeZone(timezone);

    return formatter.format(date);
}
项目:cyberduck    文件:FTPParserSelector.java   
public CompositeFileEntryParser getParser(final String system, final TimeZone zone) {
    if(log.isDebugEnabled()) {
        log.debug(String.format("Select parser for system %s in zone %s", system, zone));
    }
    final CompositeFileEntryParser parser;
    if(null == zone) {
        parser = new FTPParserFactory().createFileEntryParser(system,
                TimeZone.getTimeZone(PreferencesFactory.get().getProperty("ftp.timezone.default")));
    }
    else {
        parser = new FTPParserFactory().createFileEntryParser(system, zone);
    }
    // Configure timezone
    parser.configure(null);
    return parser;
}
项目:the-vigilantes    文件:ServerPreparedStatement.java   
private void setTimestampInternal(int parameterIndex, java.sql.Timestamp x, Calendar targetCalendar, TimeZone tz, boolean rollForward) throws SQLException {
    if (x == null) {
        setNull(parameterIndex, java.sql.Types.TIMESTAMP);
    } else {
        BindValue binding = getBinding(parameterIndex, false);
        resetToType(binding, MysqlDefs.FIELD_TYPE_DATETIME);

        if (!this.sendFractionalSeconds) {
            x = TimeUtil.truncateFractionalSeconds(x);
        }

        if (!this.useLegacyDatetimeCode) {
            binding.value = x;
        } else {
            Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? this.connection.getUtcCalendar()
                    : getCalendarInstanceForSessionOrNew();

            binding.value = TimeUtil.changeTimezone(this.connection, sessionCalendar, targetCalendar, x, tz, this.connection.getServerTimezoneTZ(),
                    rollForward);
        }
    }
}
项目:lams    文件:FastDateFormat.java   
/**
 * <p>Gets the time zone display name, using a cache for performance.</p>
 * 
 * @param tz  the zone to query
 * @param daylight  true if daylight savings
 * @param style  the style to use <code>TimeZone.LONG</code>
 *  or <code>TimeZone.SHORT</code>
 * @param locale  the locale to use
 * @return the textual name of the time zone
 */
static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
    Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
    String value = (String) cTimeZoneDisplayCache.get(key);
    if (value == null) {
        // This is a very slow call, so cache the results.
        value = tz.getDisplayName(daylight, style, locale);
        cTimeZoneDisplayCache.put(key, value);
    }
    return value;
}
项目:cyberduck    文件:S3UrlProvider.java   
/**
 * Query string authentication. Query string authentication is useful for giving HTTP or
 * browser access to resources that would normally require authentication. The signature in the query
 * string secures the request.
 *
 * @param seconds Expire in n seconds from now in default timezone
 * @return A signed URL with a limited validity over time.
 */
protected DescriptiveUrl sign(final Path file, final int seconds) {
    // Determine expiry time for URL
    final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    expiry.add(Calendar.SECOND, seconds);
    final String secret = store.findLoginPassword(session.getHost());
    if(StringUtils.isBlank(secret)) {
        log.warn("No secret found in keychain required to sign temporary URL");
        return DescriptiveUrl.EMPTY;
    }
    String region = null;
    if(session.isConnected()) {
        region = session.getClient().getRegionEndpointCache()
                .getRegionForBucketName(containerService.getContainer(file).getName());
    }
    return new DescriptiveUrl(URI.create(new S3PresignedUrlProvider().create(
            session.getHost(),
            session.getHost().getCredentials().getUsername(), secret,
            containerService.getContainer(file).getName(), region, containerService.getKey(file),
            expiry.getTimeInMillis())), DescriptiveUrl.Type.signed,
            MessageFormat.format(LocaleFactory.localizedString("{0} URL"), LocaleFactory.localizedString("Pre-Signed", "S3"))
                    + " (" + MessageFormat.format(LocaleFactory.localizedString("Expires {0}", "S3") + ")",
                    UserDateFormatterFactory.get().getMediumFormat(expiry.getTimeInMillis()))
    );
}
项目:logistimo-web-service    文件:LocalDateUtil.java   
public static Date parseDate(String timestampStr, List<String> dateFormats, String timezone)
    throws ParseException {
  Date date = null;
  SimpleDateFormat sdf = new SimpleDateFormat();
  for (String s : dateFormats) {
    sdf.applyPattern(s);
    if (timezone != null && !timezone.isEmpty()) {
      sdf.setTimeZone(TimeZone.getTimeZone(timezone));
    }
    try {
      date = sdf.parse(timestampStr);
    } catch (ParseException ignored) {
      //do nothing
    }
  }
  if (date == null) {
    throw new ParseException(timestampStr, 0);
  }
  return date;
}
项目:sunbird-lms-mw    文件:BaseMetricsActor.java   
protected static Map<String, Object> getStartAndEndDateForWeek(String period) {
  Map<String, Object> dateMap = new HashMap<>();
  Map<String, Integer> periodMap = getDaysByPeriodStr(period);
  Calendar calendar = Calendar.getInstance();
  calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
  int firstDayOfWeek = calendar.getFirstDayOfWeek();        
  calendar.add(Calendar.DATE, -(calendar.get(Calendar.DAY_OF_WEEK)-firstDayOfWeek));
  calendar.add(Calendar.WEEK_OF_YEAR, 1);
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
  String endDateStr = sdf.format(calendar.getTime());
  dateMap.put(endDate, endDateStr);
  dateMap.put(endTimeMilis, calendar.getTimeInMillis());
  calendar.add(periodMap.get(KEY), -(periodMap.get(VALUE)));
  calendar.add(Calendar.DATE, 1);
  calendar.set(Calendar.HOUR_OF_DAY,0);
  calendar.set(Calendar.MINUTE, 0);
  calendar.set(Calendar.SECOND, 0);
  calendar.set(Calendar.MILLISECOND, 0);
  dateMap.put(INTERVAL, "1w");
  dateMap.put(FORMAT, "yyyy-ww");
  String startDateStr = sdf.format(calendar.getTime());
  dateMap.put(startDate, startDateStr);
  dateMap.put(startTimeMilis, calendar.getTimeInMillis());
  return dateMap;
}
项目:backend.ai-client-java    文件:AuthTest.java   
@Test
public void getCredentialString() {
    ClientConfig config = new ClientConfig.Builder().accessKey("TESTESTSERSERESTSET").secretKey("KJSAKDFJASKFDJASDFJSAFDJSJFSAJFSDF").build();

    Auth auth = new Auth(config);
    String body = "";

    SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    ISO8601DATEFORMAT.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    String date_s = "2017-10-28T19:57:56";
    Date date = new Date();
    try {
        date = ISO8601DATEFORMAT.parse(date_s);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    String a = auth.getCredentialString("POST", "/v2/kernel/create", date, body);
    assertEquals(a, "TESTESTSERSERESTSET:dcd926f4b281e05d384b3debccd540b1cd9ad30c184f5797057616f3b86b2cc3");

}
项目:decoy    文件:TimeUtil.java   
public static String getBeijingNowTime(String format) {
    TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");

    Date date = new Date(currentTimeMillis());
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
    formatter.setTimeZone(timezone);

    return formatter.format(date);
}
项目:letv    文件:TimeUtils.java   
public static String toLocal(String utc) {
    String pattern = "yyyyMMddHHmmss";
    try {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        formater.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = formater.parse(utc);
        formater.setTimeZone(TimeZone.getDefault());
        return formater.format(date);
    } catch (Exception e) {
        LOG.i(TAG, "[utc:" + utc + "] UTC to local failed(Exception)", e);
        return "";
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:SSIMediator.java   
protected void setDateVariables(boolean fromConstructor) {
    boolean alreadySet = ssiExternalResolver.getVariableValue(className
            + ".alreadyset") != null;
    //skip this if we are being called from the constructor, and this has
    // already
    // been set
    if (!(fromConstructor && alreadySet)) {
        ssiExternalResolver.setVariableValue(className + ".alreadyset",
                "true");
        Date date = new Date();
        TimeZone timeZone = TimeZone.getTimeZone("GMT");
        String retVal = formatDate(date, timeZone);
        //If we are setting on of the date variables, we want to remove
        // them from the
        // user
        //defined list of variables, because this is what Apache does
        setVariableValue("DATE_GMT", null);
        ssiExternalResolver.setVariableValue(className + ".DATE_GMT",
                retVal);
        retVal = formatDate(date, null);
        setVariableValue("DATE_LOCAL", null);
        ssiExternalResolver.setVariableValue(className + ".DATE_LOCAL",
                retVal);
        retVal = formatDate(new Date(lastModifiedDate), null);
        setVariableValue("LAST_MODIFIED", null);
        ssiExternalResolver.setVariableValue(className + ".LAST_MODIFIED",
                retVal);
    }
}
项目:generator-thundr-gae-react    文件:OffsetDateTimeDateTranslatorFactoryTest.java   
@Test
public void load_willReturnZonedDate_whenSystemDateTimeIsNotUTC() throws Exception {
    new ExecuteAsTimeZone(TimeZone.getTimeZone(ZoneOffset.ofHours(10)))
            .run(() -> assertThat(
                    load(date("2017-08-28T07:09:36Z"))
                            .isEqual(OffsetDateTime.of(2017, 8, 28, 17, 9, 36, 0, ZoneOffset.ofHours(10))),
                    is(true)
            ));
}
项目:fitnotifications    文件:BasicDurationFormatterFactory.java   
/**
 * Set the name of the locale that will be used when
 * creating new formatters.
 *
 * @param timeZone The time zone to use.
 * @return this BasicDurationFormatterFactory
 */
@Override
public DurationFormatterFactory setTimeZone(TimeZone timeZone) {
  if (!timeZone.equals(this.timeZone)) {
    this.timeZone = timeZone;
    if (builder != null) {
        builder = builder.withTimeZone(timeZone);
    }
    reset();
  }
  return this;
}
项目:alexa-skill    文件:CalendarServiceTest.java   
@Test
public void getEvents() throws IOException, CalendarReadException {
  //given
  final CalendarCLIAdapter calendarOne = mock(CalendarCLIAdapter.class);
  final CalendarCLIAdapter calendarTwo = mock(CalendarCLIAdapter.class);
  final Map<String, CalendarCLIAdapter> calendars = new HashMap<>();
  calendars.put("one", calendarOne);
  calendars.put("two", calendarTwo);

  doReturn(TimeZone.getTimeZone("UTC")).when(calendarOne).getDefaultTimeZone();
  doReturn(TimeZone.getTimeZone("Europe/Berlin")).when(calendarTwo).getDefaultTimeZone();
  when(calendarOne.readAgenda(any(), any()))
      .thenReturn(Arrays.asList("<cal1-event1>", "<cal1-event2>"));
  when(calendarTwo.readAgenda(any(), any()))
      .thenReturn(Arrays.asList("<cal2-event1>"));
  doReturn(calendars).when(toTest).getCalendars();

  List<VEvent> cal1Event1 = Arrays.asList(e("cal1e1", DateTime.parse("2000-01-01")));
  List<VEvent> cal1Event2 = Arrays.asList(e("cal1e2", DateTime.parse("2010-01-01")), e("cal1e3", DateTime.parse("2000-01-02")));
  List<VEvent> cal2Event1 = Arrays.asList(e("cal2e1", DateTime.parse("2000-01-01")));

  doReturn(cal1Event1).when(parser).parseEvent(eq("<cal1-event1>"));
  doReturn(cal1Event2).when(parser).parseEvent(eq("<cal1-event2>"));
  doReturn(cal2Event1).when(parser).parseEvent(eq("<cal2-event1>"));

  //when
  final DateTime from = DateTime.now();
  final DateTime to = DateTime.now().plusDays(1);

  final List<Event> results = toTest.getEvents(from, to);

  //then
  verify(calendarOne, times(1)).readAgenda(from, to);
  verify(calendarTwo, times(1)).readAgenda(from, to);
  assertEquals("cal1e1", results.get(0).getSummary());
  assertEquals("cal2e1", results.get(1).getSummary());
  assertEquals("cal1e3", results.get(2).getSummary());
  assertEquals("cal1e2", results.get(3).getSummary());
}
项目:jdk8u-jdk    文件:TestZoneId.java   
@Test(expectedExceptions = DateTimeException.class)
public void test_systemDefault_unableToConvert_badFormat() {
    TimeZone current = TimeZone.getDefault();
    try {
        TimeZone.setDefault(new SimpleTimeZone(127, "Something Weird"));
        ZoneId.systemDefault();
    } finally {
        TimeZone.setDefault(current);
    }
}
项目:BibliotecaPS    文件:BufferRow.java   
@Override
public Timestamp getNativeTimestamp(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs)
        throws SQLException {
    if (isNull(columnIndex)) {
        return null;
    }

    findAndSeekToOffset(columnIndex);

    long length = this.rowFromServer.readFieldLength();

    int offset = this.rowFromServer.getPosition();

    return getNativeTimestamp(this.rowFromServer.getByteBuffer(), offset, (int) length, targetCalendar, tz, rollForward, conn, rs);
}
项目:EosCommander    文件:SignedTransaction.java   
public static Date getExpirationAsDate(String dateStr) {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf.parse( dateStr);

    } catch (ParseException e) {
        e.printStackTrace();
        return new Date();
    }
}
项目:openjdk-jdk10    文件:TestZoneId.java   
@Test(expectedExceptions = DateTimeException.class)
public void test_systemDefault_unableToConvert_badFormat() {
    TimeZone current = TimeZone.getDefault();
    try {
        TimeZone.setDefault(new SimpleTimeZone(127, "Something Weird"));
        ZoneId.systemDefault();
    } finally {
        TimeZone.setDefault(current);
    }
}
项目:logistimo-web-service    文件:DaySlice.java   
@Override
public void setDate(Date d, String tz, String freq) {
  Calendar
      cal =
      tz != null ? GregorianCalendar.getInstance(TimeZone.getTimeZone(tz))
          : GregorianCalendar.getInstance();
  cal.setTime(d);
  this.d = LocalDateUtil.getGMTZeroTimeFromCal(cal);
}
项目:Equella    文件:CourseDefaultsSettings.java   
/**
 * On a parse error, rethrow
 * 
 * @param dateAsString
 * @return A UTC Date
 */
@Nullable
public static Date parseDate(@Nullable String dateAsString) throws ParseException
{
    if( Check.isEmpty(dateAsString) )
    {
        return null;
    }
    SimpleDateFormat dateFormat = new SimpleDateFormat(COURSE_DEFAULT_DATE_FMT);
    dateFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
    return dateFormat.parse(dateAsString);
}
项目:dropwizard-mybatis    文件:ESTDateTypeHandler.java   
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i,
        Object o, JdbcType jdbcType) throws SQLException {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_WITH_Z);
    sdf.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
    if (o instanceof Date) {
        preparedStatement.setObject(i, sdf.format((Date) o), Types.TIMESTAMP);
    } else {
        throw new IllegalArgumentException("Object value is not a valid Date: " + o.toString());
    }
}
项目:cactoos    文件:DateAsTextTest.java   
@Test
public final void testDateFormattedUsingCustomFormat() {
    final Calendar calendar =
        Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.set(2017, Calendar.DECEMBER, 13, 14, 15, 16);
    MatcherAssert.assertThat(
        "Can't format a java.util.Date with custom format.",
        new DateAsText(
            calendar.getTime(), "yyyy MM dd hh:mm:ss"
        ).asString(),
        Matchers.is("2017 12 13 02:15:16")
    );
}
项目:googlecloud-techtalk    文件:SetupAppengine.java   
@Override
protected void before() throws Throwable {
    List<LocalServiceTestConfig> testConfigs = createTestConfigs();
    helper = new LocalServiceTestHelper(testConfigs.toArray(new LocalServiceTestConfig[0]));
    helper.setTimeZone(TimeZone.getDefault());
    helper.setUp();
}
项目:GitHub    文件:RealmJsonTests.java   
@Test
public void createObjectFromJson_primitiveList_mixedValues() throws JSONException, IOException {
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_STRING_LIST, new String[] {"a", null, "bc"});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_BOOLEAN_LIST, new Boolean[] {true, null, false});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_DOUBLE_LIST, new Double[] {1.0d, null, 2.0d});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_FLOAT_LIST, new Float[] {1.0f, null, 2.0f});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_BYTE_LIST, new Byte[] {1, null, 2});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_SHORT_LIST, new Short[] {1, null, 2});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_INT_LIST, new Integer[] {1, null, 2});
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_LONG_LIST, new Long[] {1L, null, 2L});

    // Date as integer
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_DATE_LIST,
            new Integer[] {0, null, 1},
            new Date[] {new Date(0), null, new Date(1)});
    // Date as String
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_DATE_LIST,
            new String [] {"/Date(1000)/", null, "/Date(2000)/"},
            new Date[] {new Date(1000), null, new Date(2000)});
    // Date as String timezone
    // Oct 03 2015 14:45.33
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("Australia/West"));
    cal.set(2015, Calendar.OCTOBER, 3, 14, 45, 33);
    cal.set(Calendar.MILLISECOND, 376);
    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_DATE_LIST,
            new String [] {"/Date(1443854733376+0800)/", null},
            new Date[] {cal.getTime(), null});


    testPrimitiveListWithValues(PrimitiveListTypes.FIELD_BINARY_LIST,
            new String[] {new String(Base64.encode(new byte[] {1, 2, 3}, Base64.DEFAULT), UTF_8),
                    null, new String(Base64.encode(new byte[] {4, 5, 6}, Base64.DEFAULT), UTF_8)},
            new byte[][] {new byte[]{1, 2, 3}, null, new byte[]{4, 5, 6}});
}
项目:JKCloud    文件:DateUtil.java   
/**
 * 将字符串转位日期类型
 *
 * @param sdate
 * @return
 */
public static Date toDate(String sdate) {
    try {
        String date = sdate.replace("T", " ");
        date = date.replace("Z", "");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        // Date date = formatter.parse(time);
        return dateFormater.get().parse(date);
    } catch (ParseException e) {
        return null;
    }
}
项目:oscm    文件:DateConverterTest.java   
@Test
public void getStartOfWeek() {
    // given
    TimeZone.setDefault(TimeZone.getTimeZone("GMT"));

    // when (Mon, 10 Dec 2012 02:00:00 GMT)
    Calendar startOfWeek = DateConverter.getStartOfWeek(1355104800000L);

    // then
    assertEquals(1355097600000L, startOfWeek.getTimeInMillis());
}
项目:mvvm-template    文件:GsonProvider.java   
@Override
public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    String date = element.getAsString();
    SimpleDateFormat formatter = new SimpleDateFormat(RemoteConstants.DATE_TIME_FORMAT, Locale.getDefault());
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
        return formatter.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}
项目:BibliotecaPS    文件:BufferRow.java   
@Override
public Time getNativeTime(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs)
        throws SQLException {
    if (isNull(columnIndex)) {
        return null;
    }

    findAndSeekToOffset(columnIndex);

    long length = this.rowFromServer.readFieldLength();

    int offset = this.rowFromServer.getPosition();

    return getNativeTime(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int) length, targetCalendar, tz, rollForward, conn, rs);
}
项目:grammaticus    文件:GrammaticalLocalizerFactory.java   
@Override
public BaseLocalizer getLocalizer(Locale locale, Locale currencyLocale, HumanLanguage language, TimeZone timeZone) {
       if (locale == null)
           locale = getDefaultLocale();
       if (language == null)
           language = getDefaultLanguage();

       GrammaticalLabelSet labelSet = (GrammaticalLabelSet) findLabelSet(language);
       return new GrammaticalLocalizer(locale, currencyLocale, timeZone, language, labelSet);
   }
项目:data-binding-validator    文件:DateValidator.java   
/**
 * <p>Convert a <code>Date</code> to a <code>Calendar</code>.</p>
 *
 * @param value The date value to be converted.
 * @return The converted <code>Calendar</code>.
 */
private Calendar getCalendar(Date value, TimeZone timeZone) {

    Calendar calendar = null;
    if (timeZone != null) {
        calendar = Calendar.getInstance(timeZone);
    } else {
        calendar = Calendar.getInstance();
    }
    calendar.setTime(value);
    return calendar;

}
项目:openjdk-jdk10    文件:InternationalBAT.java   
private static boolean testRequiredLocales() {
    boolean pass = true;

    TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
    Calendar calendar = Calendar.getInstance(Locale.US);
    calendar.clear();
    calendar.set(2001, 4, 10, 12, 0, 0);
    Date date = calendar.getTime();

    Locale[] available = Locale.getAvailableLocales();
    for (int i = 0; i < requiredLocales.length; i++) {
        Locale locale = requiredLocales[i];
        boolean found = false;
        for (int j = 0; j < available.length; j++) {
            if (available[j].equals(locale)) {
                found = true;
                break;
            }
        }
        if (!found) {
            System.out.println("Locale not available: " + locale);
            pass = false;
        } else {
            DateFormat format =
                    DateFormat.getDateInstance(DateFormat.FULL, locale);
            String dateString = format.format(date);
            if (!dateString.equals(requiredLocaleDates[i])) {
                System.out.println("Incorrect date string for locale "
                        + locale + ". Expected: " + requiredLocaleDates[i]
                        + ", got: " + dateString);
                pass = false;
            }
        }
    }
    return pass;
}
项目:calcite-avatica    文件:DateTimeUtils.java   
@Deprecated // to be removed before 2.0
public static PrecisionTime parsePrecisionDateTimeLiteral(
    String s,
    String pattern,
    TimeZone tz) {
  assert pattern != null;
  return parsePrecisionDateTimeLiteral(s,
      new SimpleDateFormat(pattern, Locale.ROOT), tz, 3);
}
项目:morpheus-core    文件:SparseArrayConstructor.java   
@Override
@SuppressWarnings("unchecked")
public <T> Array<T> apply(Class<T> type, int length, T defaultValue, String path) {
    if (type.isEnum()) {
        final IntCoding<T> enumCoding = (IntCoding<T>)IntCoding.ofEnum((Class<Enum>)type);
        return new SparseArrayWithIntCoding<>(length, defaultValue, enumCoding);
    } else {
        switch (ArrayType.of(type)) {
            case BOOLEAN:           return ArrayFactory.dense().apply(type, length, defaultValue, null);
            case INTEGER:           return (Array<T>)new SparseArrayOfInts(length, (Integer)defaultValue);
            case LONG:              return (Array<T>)new SparseArrayOfLongs(length, (Long)defaultValue);
            case DOUBLE:            return (Array<T>)new SparseArrayOfDoubles(length, (Double)defaultValue);
            case OBJECT:            return (Array<T>)new SparseArrayOfObjects(type, length, defaultValue);
            case STRING:            return (Array<T>)new SparseArrayOfObjects(type, length, defaultValue);
            case LOCAL_DATE:        return (Array<T>)new SparseArrayWithLongCoding<>(length, (LocalDate)defaultValue, localDateCoding);
            case LOCAL_TIME:        return (Array<T>)new SparseArrayWithLongCoding<>(length, (LocalTime)defaultValue, localTimeCoding);
            case LOCAL_DATETIME:    return (Array<T>)new SparseArrayWithLongCoding<>(length, (LocalDateTime)defaultValue, localDateTimeCoding);
            case YEAR:              return (Array<T>)new SparseArrayWithIntCoding<>(length, (Year)defaultValue, yearCoding);
            case ZONE_ID:           return (Array<T>)new SparseArrayWithIntCoding<>(length, (ZoneId)defaultValue, zoneIdCoding);
            case TIME_ZONE:         return (Array<T>)new SparseArrayWithIntCoding<>(length, (TimeZone)defaultValue, timeZoneCoding);
            case DATE:              return (Array<T>)new SparseArrayWithLongCoding<>(length, (Date)defaultValue, dateCoding);
            case INSTANT:           return (Array<T>)new SparseArrayWithLongCoding<>(length, (Instant)defaultValue, instantCoding);
            case CURRENCY:          return (Array<T>)new SparseArrayWithIntCoding<>(length, (Currency)defaultValue, currencyCoding);
            case ZONED_DATETIME:    return (Array<T>)new SparseArrayOfZonedDateTimes(length, (ZonedDateTime) defaultValue);
            default:                return (Array<T>)new SparseArrayOfObjects(type, length, defaultValue);
        }
    }
}
项目:openjdk-jdk10    文件:DisabledAlgorithmConstraints.java   
DenyAfterConstraint(String algo, int year, int month, int day) {
    Calendar c;

    algorithm = algo;

    if (debug != null) {
        debug.println("DenyAfterConstraint read in as:  year " +
                year + ", month = " + month + ", day = " + day);
    }

    c = new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("GMT"))
            .setDate(year, month - 1, day).build();

    if (year > c.getActualMaximum(Calendar.YEAR) ||
            year < c.getActualMinimum(Calendar.YEAR)) {
        throw new IllegalArgumentException(
                "Invalid year given in constraint: " + year);
    }
    if ((month - 1) > c.getActualMaximum(Calendar.MONTH) ||
            (month - 1) < c.getActualMinimum(Calendar.MONTH)) {
        throw new IllegalArgumentException(
                "Invalid month given in constraint: " + month);
    }
    if (day > c.getActualMaximum(Calendar.DAY_OF_MONTH) ||
            day < c.getActualMinimum(Calendar.DAY_OF_MONTH)) {
        throw new IllegalArgumentException(
                "Invalid Day of Month given in constraint: " + day);
    }

    denyAfterDate = c.getTime();
    if (debug != null) {
        debug.println("DenyAfterConstraint date set to: " +
                dateFormat.format(denyAfterDate));
    }
}