Java Code Examples for org.joda.time.DateTimeZone#forTimeZone()

The following examples show how to use org.joda.time.DateTimeZone#forTimeZone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimeUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getIsoDateWithLocalTime(Date dateToConvert) {
    if (dateToConvert == null) {
        return null;
    }
    DateTime dt = new DateTime(dateToConvert);
    DateTimeFormatter fmt = ISODateTimeFormat.yearMonthDay();
    DateTimeFormatter localFmt = fmt.withLocale(new ResourceLoader().getLocale());
    DateTimeFormatter fmtTime = DateTimeFormat.shortTime();
    DateTimeFormatter localFmtTime = fmtTime.withLocale(new ResourceLoader().getLocale());

    // If the client browser is in a different timezone than server, need to modify date
    if (m_client_timezone !=null && m_server_timezone!=null && !m_client_timezone.hasSameRules(m_server_timezone)) {
      DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(m_client_timezone);
      localFmt = localFmt.withZone(dateTimeZone);
      localFmtTime = localFmtTime.withZone(dateTimeZone);
    }
    return dt.toString(localFmt) + " " + dt.toString(localFmtTime);
}
 
Example 2
Source File: TestPrestoDriver.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetTimeZoneId()
        throws Exception
{
    TimeZoneKey defaultZoneKey = TimeZoneKey.getTimeZoneKey(TimeZone.getDefault().getID());
    DateTimeZone defaultZone = DateTimeZone.forTimeZone(TimeZone.getDefault());
    String sql = "SELECT current_timezone() zone, TIMESTAMP '2001-02-03 3:04:05' ts";

    try (Connection connection = createConnection()) {
        try (Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(sql)) {
            assertTrue(rs.next());
            assertEquals(rs.getString("zone"), defaultZoneKey.getId());
            assertEquals(rs.getTimestamp("ts"), new Timestamp(new DateTime(2001, 2, 3, 3, 4, 5, defaultZone).getMillis()));
        }

        connection.unwrap(PrestoConnection.class).setTimeZoneId("UTC");
        try (Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(sql)) {
            assertTrue(rs.next());
            assertEquals(rs.getString("zone"), "UTC");
            assertEquals(rs.getTimestamp("ts"), new Timestamp(new DateTime(2001, 2, 3, 3, 4, 5, DateTimeZone.UTC).getMillis()));
        }
    }
}
 
Example 3
Source File: GanttTest.java    From gantt with Apache License 2.0 6 votes vote down vote up
@Test
public void setDateRangeForDayResolutionAndDefaultTimezoneTest_TimeZonePacificHonolulu() {
    Gantt gantt = new Gantt();
    gantt.setResolution(Resolution.Day);
    gantt.setTimeZone(TimeZone.getTimeZone("Pacific/Honolulu"));

    DateTimeZone tz = DateTimeZone.forTimeZone(TimeZone
            .getTimeZone("Pacific/Honolulu"));

    DateTime expectedStart = new DateTime(2014, 1, 1, 0, 0, 0, 000, tz);
    DateTime expectedEnd = new DateTime(2015, 1, 1, 23, 59, 59, 999, tz);

    DateTime start = new DateTime(2014, 1, 1, 10, 30, 30, 123, tz);
    DateTime end = new DateTime(2015, 1, 1, 10, 30, 30, 123, tz);

    gantt.setStartDate(start.toDate());
    gantt.setEndDate(end.toDate());

    Assert.assertEquals(expectedStart.toDate(), gantt.getStartDate());
    Assert.assertEquals(expectedEnd.toDate(), gantt.getEndDate());
}
 
Example 4
Source File: DateTimeFormatPatternSpec.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public DateTimeFormatPatternSpec(String timeFormat, String sdfPatternWithTz) {
  _timeFormat = TimeFormat.valueOf(timeFormat);
  if (_timeFormat.equals(TimeFormat.SIMPLE_DATE_FORMAT)) {
    Matcher m = SDF_PATTERN_WITH_TIMEZONE.matcher(sdfPatternWithTz);
    _sdfPattern = sdfPatternWithTz;
    if (m.find()) {
      _sdfPattern = m.group(SDF_PATTERN_GROUP).trim();
      String timezoneString = m.group(TIMEZONE_GROUP).trim();
      _dateTimeZone = DateTimeZone.forTimeZone(TimeZone.getTimeZone(timezoneString));
    }
    _dateTimeFormatter = DateTimeFormat.forPattern(_sdfPattern).withZone(_dateTimeZone).withLocale(DEFAULT_LOCALE);
  }
}
 
Example 5
Source File: CalendarUtilTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testLocalPMString() {
    // This is to test that the schedule tool works through GMT -> BST transitions
    DateTimeZone zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/London"));
    // This a day that the clocks go forward in London
    DateTime dateTime = new DateTime(2015, 3, 29, 16,0, zone);
    assertEquals("PM", CalendarUtil.getLocalPMString(dateTime));
}
 
Example 6
Source File: PreparedStatementFieldMapperFactoryTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testJodaLocalTime() throws Exception {
    org.joda.time.LocalTime value = new org.joda.time.LocalTime();
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

    newFieldMapperAndMapToPS(new ConstantGetter<Object, org.joda.time.LocalTime>(value), org.joda.time.LocalTime.class, dateTimeZone);
    newFieldMapperAndMapToPS(NullGetter.<Object,  org.joda.time.LocalTime>getter(), org.joda.time.LocalTime.class);

    verify(ps).setTime(1, new Time(value.toDateTimeToday(dateTimeZone).getMillis()));
    verify(ps).setNull(2, Types.TIME);
}
 
Example 7
Source File: AbstractJodaProcessorBuilder.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * 変換規則から、{@link DateTimeFormatter}のインスタンスを作成する。
 * <p>アノテーション{@link CsvDateTimeFormat}が付与されていない場合は、各種タイプごとの標準の書式で作成する。</p>
 * @param field フィールド情報
 * @param config システム設定
 * @return {@link DateTimeFormatter}のインスタンス。
 */
protected DateTimeFormatter createFormatter(final FieldAccessor field, final Configuration config) {
    
    final Optional<CsvDateTimeFormat> formatAnno = field.getAnnotation(CsvDateTimeFormat.class);
    if(!formatAnno.isPresent()) {
        return DateTimeFormat.forPattern(getDefaultPattern());
    }
    
    String pattern = formatAnno.get().pattern();
    if(pattern.isEmpty()) {
        pattern = getDefaultPattern();
    }
    
    final Locale locale = Utils.getLocale(formatAnno.get().locale());
    final DateTimeZone zone = formatAnno.get().timezone().isEmpty() ? DateTimeZone.getDefault()
            : DateTimeZone.forTimeZone(TimeZone.getTimeZone(formatAnno.get().timezone()));
    
    final DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern)
            .withLocale(locale)
            .withZone(zone);
    
    final boolean lenient = formatAnno.get().lenient();
    if(lenient) {
        Chronology chronology = LenientChronology.getInstance(ISOChronology.getInstance());
        return formatter.withChronology(chronology);
        
    } else {
        return formatter;
    }
    
}
 
Example 8
Source File: Utils.java    From Course_Generator with GNU General Public License v3.0 5 votes vote down vote up
public static DateTime determineSunsetTimes(DateTime StartTime, double latitude, double longitude,
		String timeZoneId) {
	// Because giving a date with a specific hour could result into getting the
	// sunrise of the previous day,
	// we adjust the date to the beginning of the day
	DateTime beginningOfDay = new DateTime(StartTime.getYear(), StartTime.getMonthOfYear(),
			StartTime.getDayOfMonth(), 0, 0, DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZoneId)));

	SunTimes times = SunTimes.compute().on(beginningOfDay.toDate()).at(latitude, longitude).execute();

	DateTime sunsetTime = new DateTime(times.getSet())
			.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZoneId)));
	return sunsetTime;

}
 
Example 9
Source File: TimeZoneInfo.java    From es6draft with MIT License 5 votes vote down vote up
private static DateTimeZone toDateTimeZone(TimeZone tz) {
    TimeZoneRef<DateTimeZone> ref = lastTimeZone;
    String id = tz.getID();
    DateTimeZone timeZone = ref.get(id);
    if (timeZone != null) {
        return timeZone;
    }
    timeZone = DateTimeZone.forTimeZone(tz);
    lastTimeZone = new TimeZoneRef<>(id, timeZone);
    return timeZone;
}
 
Example 10
Source File: SensorbergTestRunner.java    From android-sdk with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle arguments) {
    MultiDex.install(getTargetContext());

    super.onCreate(arguments);
    System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath());

    if (com.sensorberg.sdk.BuildConfig.RESOLVER_URL != null) {
        RetrofitApiTransport.RESOLVER_BASE_URL = com.sensorberg.sdk.BuildConfig.RESOLVER_URL;
    }
    JodaTimeAndroid.init(getContext());

    DateTimeZone e = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+01:00"));
    DateTimeZone.setDefault(e);
}
 
Example 11
Source File: TimeMetaData.java    From DataVec with Apache License 2.0 5 votes vote down vote up
/**
 * @param timeZone     Timezone for this column. Typically used for parsing and some transforms
 * @param minValidTime Minimum valid time, in milliseconds (timestamp format). If null: no restriction
 * @param maxValidTime Maximum valid time, in milliseconds (timestamp format). If null: no restriction
 */
public TimeMetaData(String name, TimeZone timeZone, Long minValidTime, Long maxValidTime) {
    super(name);
    this.timeZone = DateTimeZone.forTimeZone(timeZone);
    this.minValidTime = minValidTime;
    this.maxValidTime = maxValidTime;
}
 
Example 12
Source File: PreparedStatementFieldMapperFactoryTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testJodaLocalDateTime() throws Exception {
    org.joda.time.LocalDateTime value = new org.joda.time.LocalDateTime();
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

    newFieldMapperAndMapToPS(new ConstantGetter<Object, org.joda.time.LocalDateTime>(value), org.joda.time.LocalDateTime.class, dateTimeZone);
    newFieldMapperAndMapToPS(NullGetter.<Object,  org.joda.time.LocalDateTime>getter(), org.joda.time.LocalDateTime.class);

    verify(ps).setTimestamp(1, new Timestamp(value.toDateTime(dateTimeZone).getMillis()));
    verify(ps).setNull(2, Types.TIMESTAMP);
}
 
Example 13
Source File: TimestampYearCalculator.java    From reladomo with Apache License 2.0 5 votes vote down vote up
@Override
public Operation optimizedIntegerEq(int value, CalculatedIntegerAttribute intAttribute)
{
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(MithraTimestamp.DefaultTimeZone);
    DateTime dateBefore = new DateTime().withZone(dateTimeZone).withYear(value).withDayOfMonth(1).withMonthOfYear(1).withTimeAtStartOfDay();
    DateTime dateAfter = new DateTime().withZone(dateTimeZone).withYear(value + 1).withDayOfMonth(1).withMonthOfYear(1).withTimeAtStartOfDay();

    Timestamp timestampBefore = new Timestamp(dateBefore.getMillis());
    Timestamp timestampAfter = new Timestamp(dateAfter.getMillis());

    return this.attribute.greaterThanEquals(timestampBefore).and(attribute.lessThan(timestampAfter));
}
 
Example 14
Source File: DateTimeFormatterFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void createDateTimeFormatterWithTimeZone() throws Exception {
	factory.setPattern("yyyyMMddHHmmss Z");
	factory.setTimeZone(TEST_TIMEZONE);
	DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TEST_TIMEZONE);
	DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
	String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200");
	assertThat(factory.createDateTimeFormatter().print(dateTime), is("20091021121000 " + offset));
}
 
Example 15
Source File: CalendarUtilTest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testLocalPMStringStartOfDay() {
    // This is to test that the schedule tool works through GMT -> BST transitions
    DateTimeZone zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/London"));
    // This a day that the clocks go forward in London
    DateTime dateTime = new DateTime(2015, 3, 29, 0, 0, zone);
    assertEquals("PM", CalendarUtil.getLocalPMString(dateTime));
}
 
Example 16
Source File: DataTypeDate.java    From ClickHouse-Native-JDBC with Apache License 2.0 5 votes vote down vote up
public DataTypeDate(PhysicalInfo.ServerInfo serverInfo) {
    if (!java.lang.Boolean.TRUE
             .equals(serverInfo.getConfigure().settings().get(SettingKey.use_client_time_zone))) {
        this.dateTimeZone = DateTimeZone.forTimeZone(serverInfo.timeZone());
    } else {
        this.dateTimeZone = DateTimeZone.getDefault();
    }
    this.dateFormat.setTimeZone(this.dateTimeZone.toTimeZone());
}
 
Example 17
Source File: GanttTest.java    From gantt with Apache License 2.0 5 votes vote down vote up
@Test
public void setDateRange_withDayResolutionAndTZEuropeAmsterdamAndCustomTimezoneOffsetDate() {
    Gantt gantt = new Gantt() {
        @Override
        protected Date getTimezoneOffsetDate() {
            return new DateTime(2015, 4, 1, 0, 0, 0, 000,
                    DateTimeZone.forTimeZone(TimeZone
                            .getTimeZone("Europe/Amsterdam"))).toDate();
        }
    };
    gantt.setResolution(Resolution.Day);
    gantt.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));

    DateTime expectedEnd = new DateTime(2015, 4, 30, 23, 59, 59, 999,
            DateTimeZone.forTimeZone(TimeZone
                    .getTimeZone("Europe/Amsterdam")));

    DateTime start = new DateTime(2015, 4, 1, 10, 30, 30, 123,
            DateTimeZone.forTimeZone(TimeZone
                    .getTimeZone("Europe/Amsterdam")));
    DateTime end = new DateTime(2015, 4, 30, 10, 30, 30, 123,
            DateTimeZone.forTimeZone(TimeZone
                    .getTimeZone("Europe/Amsterdam")));

    gantt.setStartDate(start.toDate());
    gantt.setEndDate(end.toDate());

    Assert.assertEquals(gantt.getEndDate(), expectedEnd.toDate());
}
 
Example 18
Source File: TemporalInstantTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
	public void constructorTest() throws Exception {
		TemporalInstant instant = new TemporalInstantRfc3339(2014, 12, 30, //
				12, 59, 59);
		// YYYY-MM-DDThh:mm:ssZ
		String stringTestDate01 = "2014-12-30T12:59:59Z";
		Date dateTestDate01 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
				.parse(stringTestDate01);
		Assert.assertEquals(stringTestDate01, instant.getAsKeyString());
		Assert.assertArrayEquals(StringUtils.getBytesUtf8(instant.getAsKeyString()), instant.getAsKeyBytes());
		Assert.assertTrue("Key must be normalized to time zone Zulu",instant.getAsKeyString().endsWith("Z"));
		// show the local time us.
		// Warning, if test is run in the London, or Zulu time zone, this test will be same as above, with the Z.
		// TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // this does not affect the library, don't use.
		String stringLocalTestDate01 = new SimpleDateFormat( 	 "yyyy-MM-dd'T'HH:mm:ssXXX").format(dateTestDate01);
		// for ET, will be: "2014-12-30T07:59:59-05:00"
		//instant.getAsDateTime().withZone(null);
//		System.out.println("===System.getProperty(user.timezone)="+System.getProperty("user.timezone")); //=ET
//		System.out.println("===============TimeZone.getDefault()="+TimeZone.getDefault());				//=ET
//		System.out.println("===========DateTimeZone.getDefault()="+DateTimeZone.getDefault());			//=UTC (wrong!)
		// the timezone default gets set to UTC by some prior test, fix it here.
		DateTimeZone newTimeZone = null;
		try {
            String id = System.getProperty("user.timezone");
            if (id != null) {
                newTimeZone = DateTimeZone.forID(id);
            }
        } catch (RuntimeException ex) {
            // ignored
        }
        if (newTimeZone == null) {
            newTimeZone = DateTimeZone.forTimeZone(TimeZone.getDefault());
        }
        DateTimeZone.setDefault(newTimeZone);
        // null timezone means use the default:
		Assert.assertEquals("Joda time library (actual) should use same local timezone as Java date (expected).",	stringLocalTestDate01, instant.getAsReadable(null));
	}
 
Example 19
Source File: TestDateTimeZone.java    From joda-time-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testForTimeZone_TimeZone() {
    assertEquals(DateTimeZone.getDefault(), DateTimeZone.forTimeZone((TimeZone) null));
    
    DateTimeZone zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/London"));
    assertEquals("Europe/London", zone.getID());
    assertSame(DateTimeZone.UTC, DateTimeZone.forTimeZone(TimeZone.getTimeZone("UTC")));
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("+00:00"));
    assertSame(DateTimeZone.UTC, zone);
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    assertSame(DateTimeZone.UTC, zone);
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    assertSame(DateTimeZone.UTC, zone);
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+00"));
    assertSame(DateTimeZone.UTC, zone);
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+01:23"));
    assertEquals("+01:23", zone.getID());
    assertEquals(DateTimeConstants.MILLIS_PER_HOUR + (23L * DateTimeConstants.MILLIS_PER_MINUTE),
            zone.getOffset(TEST_TIME_SUMMER));
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+1:23"));
    assertEquals("+01:23", zone.getID());
    assertEquals(DateTimeConstants.MILLIS_PER_HOUR + (23L * DateTimeConstants.MILLIS_PER_MINUTE),
            zone.getOffset(TEST_TIME_SUMMER));
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT-02:00"));
    assertEquals("-02:00", zone.getID());
    assertEquals((-2L * DateTimeConstants.MILLIS_PER_HOUR), zone.getOffset(TEST_TIME_SUMMER));
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+2"));
    assertEquals("+02:00", zone.getID());
    assertEquals((2L * DateTimeConstants.MILLIS_PER_HOUR), zone.getOffset(TEST_TIME_SUMMER));
    
    zone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("EST"));
    assertEquals("America/New_York", zone.getID());

    TimeZone tz = TimeZone.getTimeZone("GMT-08:00");
    tz.setID("GMT-\u0660\u0668:\u0660\u0660");
    zone = DateTimeZone.forTimeZone(tz);
    assertEquals("-08:00", zone.getID());
}
 
Example 20
Source File: GanttTest.java    From gantt with Apache License 2.0 4 votes vote down vote up
@Test
public void clientWeekNumberCalculation_lastWeekIf2014_weekNumber1() {
    TimeZone timezone = TimeZone.getTimeZone("Asia/Tehran");
    Locale locale = Locale.GERMANY;

    DateTime week1_2014 = new DateTime(2014, 1, 1, 0, 0, 0, 000,
            DateTimeZone.forTimeZone(timezone));

    DateTime week2_2014 = new DateTime(2014, 1, 6, 0, 0, 0, 000,
            DateTimeZone.forTimeZone(timezone));

    DateTime week52_2014 = new DateTime(2014, 12, 28, 0, 0, 0, 000,
            DateTimeZone.forTimeZone(timezone));

    DateTime lastDayOf2014 = new DateTime(2014, 12, 31, 0, 0, 0, 000,
            DateTimeZone.forTimeZone(timezone));

    DateTime week1_2015 = new DateTime(2015, 1, 4, 0, 0, 0, 000,
            DateTimeZone.forTimeZone(timezone));
    DateTime week2_2015 = new DateTime(2015, 1, 5, 0, 0, 0, 000,
            DateTimeZone.forTimeZone(timezone));

    Calendar cal = Calendar.getInstance(timezone, locale);

    long tzOfset = getTimezoneOffset(timezone, locale);

    int weekNumber = GanttUtil.getWeekNumber(new Date(week1_2014.toDate()
            .getTime() + tzOfset), getTimezoneOffset(timezone, locale),
            cal.getFirstDayOfWeek());
    Assert.assertEquals(1, weekNumber);

    weekNumber = GanttUtil.getWeekNumber(new Date(week2_2014.toDate()
            .getTime() + tzOfset), getTimezoneOffset(timezone, locale),
            cal.getFirstDayOfWeek());
    Assert.assertEquals(2, weekNumber);

    weekNumber = GanttUtil.getWeekNumber(lastDayOf2014.toDate(),
            getTimezoneOffset(timezone, locale), cal.getFirstDayOfWeek());
    Assert.assertEquals(1, weekNumber);

    weekNumber = GanttUtil.getWeekNumber(new Date(week52_2014.toDate()
            .getTime() + tzOfset), getTimezoneOffset(timezone, locale),
            cal.getFirstDayOfWeek());
    Assert.assertEquals(52, weekNumber);

    weekNumber = GanttUtil.getWeekNumber(new Date(week1_2015.toDate()
            .getTime() + tzOfset), getTimezoneOffset(timezone, locale),
            cal.getFirstDayOfWeek());
    Assert.assertEquals(1, weekNumber);

    weekNumber = GanttUtil.getWeekNumber(new Date(week2_2015.toDate()
            .getTime() + tzOfset), getTimezoneOffset(timezone, locale),
            cal.getFirstDayOfWeek());
    Assert.assertEquals(2, weekNumber);
}