Java Code Examples for java.util.TimeZone

The following are top voted examples for showing how to use java.util.TimeZone. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: puremadrid   File: ApiMedicion.java   View source code 7 votes vote down vote up
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;
    }
}
 
Example 2
Project: andcouchbaseentity   File: TaskActivity.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 3
Project: TimeAndMoney   File: JavaUtilCalendarQuirksTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 4
Project: spring-boot-gae   File: OffsetDateTimeStringTranslatorFactoryTest.java   View source code 6 votes vote down vote up
@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)
            ));
}
 
Example 5
Project: fitnotifications   File: YMDDateFormatter.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: ForeverLibrary   File: MiscUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: RLibrary   File: TimeUtil.java   View source code 6 votes vote down vote up
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);
}
 
Example 8
Project: cyberduck   File: FTPParserSelector.java   View source code 6 votes vote down vote up
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;
}
 
Example 9
Project: the-vigilantes   File: ServerPreparedStatement.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 10
Project: lams   File: FastDateFormat.java   View source code 6 votes vote down vote up
/**
 * <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;
}
 
Example 11
Project: cyberduck   File: S3UrlProvider.java   View source code 6 votes vote down vote up
/**
 * 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()))
    );
}
 
Example 12
Project: logistimo-web-service   File: LocalDateUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 13
Project: sunbird-lms-mw   File: BaseMetricsActor.java   View source code 6 votes vote down vote up
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;
}
 
Example 14
Project: backend.ai-client-java   File: AuthTest.java   View source code 6 votes vote down vote up
@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");

}
 
Example 15
Project: decoy   File: TimeUtil.java   View source code 5 votes vote down vote up
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);
}
 
Example 16
Project: letv   File: TimeUtils.java   View source code 5 votes vote down vote up
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 "";
    }
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: SSIMediator.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 18
Project: generator-thundr-gae-react   File: OffsetDateTimeDateTranslatorFactoryTest.java   View source code 5 votes vote down vote up
@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)
            ));
}
 
Example 19
Project: fitnotifications   File: BasicDurationFormatterFactory.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 20
Project: alexa-skill   File: CalendarServiceTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 21
Project: jdk8u-jdk   File: TestZoneId.java   View source code 5 votes vote down vote up
@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);
    }
}
 
Example 22
Project: BibliotecaPS   File: BufferRow.java   View source code 5 votes vote down vote up
@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);
}
 
Example 23
Project: EosCommander   File: SignedTransaction.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 24
Project: openjdk-jdk10   File: TestZoneId.java   View source code 5 votes vote down vote up
@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);
    }
}
 
Example 25
Project: logistimo-web-service   File: DaySlice.java   View source code 5 votes vote down vote up
@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);
}
 
Example 26
Project: Equella   File: CourseDefaultsSettings.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 27
Project: dropwizard-mybatis   File: ESTDateTypeHandler.java   View source code 5 votes vote down vote up
@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());
    }
}
 
Example 28
Project: cactoos   File: DateAsTextTest.java   View source code 5 votes vote down vote up
@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")
    );
}
 
Example 29
Project: googlecloud-techtalk   File: SetupAppengine.java   View source code 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    List<LocalServiceTestConfig> testConfigs = createTestConfigs();
    helper = new LocalServiceTestHelper(testConfigs.toArray(new LocalServiceTestConfig[0]));
    helper.setTimeZone(TimeZone.getDefault());
    helper.setUp();
}
 
Example 30
Project: GitHub   File: RealmJsonTests.java   View source code 5 votes vote down vote up
@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}});
}
 
Example 31
Project: JKCloud   File: DateUtil.java   View source code 5 votes vote down vote up
/**
 * 将字符串转位日期类型
 *
 * @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;
    }
}
 
Example 32
Project: oscm   File: DateConverterTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 33
Project: mvvm-template   File: GsonProvider.java   View source code 5 votes vote down vote up
@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;
    }
}
 
Example 34
Project: BibliotecaPS   File: BufferRow.java   View source code 5 votes vote down vote up
@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);
}
 
Example 35
Project: grammaticus   File: GrammaticalLocalizerFactory.java   View source code 5 votes vote down vote up
@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);
   }
 
Example 36
Project: data-binding-validator   File: DateValidator.java   View source code 5 votes vote down vote up
/**
 * <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;

}
 
Example 37
Project: openjdk-jdk10   File: InternationalBAT.java   View source code 5 votes vote down vote up
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;
}
 
Example 38
Project: calcite-avatica   File: DateTimeUtils.java   View source code 5 votes vote down vote up
@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);
}
 
Example 39
Project: morpheus-core   File: SparseArrayConstructor.java   View source code 5 votes vote down vote up
@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);
        }
    }
}
 
Example 40
Project: openjdk-jdk10   File: DisabledAlgorithmConstraints.java   View source code 5 votes vote down vote up
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));
    }
}