org.joda.time.DateTimeUtils Java Examples

The following examples show how to use org.joda.time.DateTimeUtils. 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: Time_6_GJChronology_t.java    From coming with MIT License 6 votes vote down vote up
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
    // overridden as superclass algorithm can't handle
    // 2004-02-29 + 48 months -> 2008-02-29 type dates
    if (valueToAdd == 0) {
        return values;
    }
    if (DateTimeUtils.isContiguous(partial)) {
        long instant = 0L;
        for (int i = 0, isize = partial.size(); i < isize; i++) {
            instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
        }
        instant = add(instant, valueToAdd);
        return GJChronology.this.get(partial, instant);
    } else {
        return super.add(partial, fieldIndex, values, valueToAdd);
    }
}
 
Example #2
Source File: WatermarkEstimatorsTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testWallTimeWatermarkEstimator() {
  DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis());
  WatermarkEstimator<Instant> watermarkEstimator =
      new WatermarkEstimators.WallTime(new Instant());
  DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1).getMillis());
  assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1), watermarkEstimator.currentWatermark());

  DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2).getMillis());
  // Make sure that we don't mutate state even if the clock advanced
  assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1), watermarkEstimator.getState());
  assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2), watermarkEstimator.currentWatermark());
  assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2), watermarkEstimator.getState());

  // Handle the case if the clock ever goes backwards. Could happen if we resumed processing
  // on a machine that had misconfigured clock or due to clock skew.
  DateTimeUtils.setCurrentMillisFixed(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(1).getMillis());
  assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE.plus(2), watermarkEstimator.currentWatermark());
}
 
Example #3
Source File: Time_18_GJChronology_t.java    From coming with MIT License 6 votes vote down vote up
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
    // overridden as superclass algorithm can't handle
    // 2004-02-29 + 48 months -> 2008-02-29 type dates
    if (valueToAdd == 0) {
        return values;
    }
    if (DateTimeUtils.isContiguous(partial)) {
        long instant = 0L;
        for (int i = 0, isize = partial.size(); i < isize; i++) {
            instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
        }
        instant = add(instant, valueToAdd);
        return GJChronology.this.get(partial, instant);
    } else {
        return super.add(partial, fieldIndex, values, valueToAdd);
    }
}
 
Example #4
Source File: GJChronology.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
    // overridden as superclass algorithm can't handle
    // 2004-02-29 + 48 months -> 2008-02-29 type dates
    if (valueToAdd == 0) {
        return values;
    }
    if (DateTimeUtils.isContiguous(partial)) {
        long instant = 0L;
        for (int i = 0, isize = partial.size(); i < isize; i++) {
            instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
        }
        instant = add(instant, valueToAdd);
        return GJChronology.this.get(partial, instant);
    } else {
        return super.add(partial, fieldIndex, values, valueToAdd);
    }
}
 
Example #5
Source File: TimestampedEvent.java    From bboss-elasticsearch with Apache License 2.0 6 votes vote down vote up
TimestampedEvent(Event base) {
	  super(base);
//    setBody(base.getBody());

    Map<String, String> headers =base.getHeaders();
    String timestampString = headers != null ?headers.get("timestamp"):null;
    if (SimpleStringUtil.isEmpty(timestampString)) {
      timestampString = headers.get("@timestamp");
    }
    if (SimpleStringUtil.isEmpty(timestampString)) {
      this.timestamp = DateTimeUtils.currentTimeMillis();
      headers.put("timestamp", String.valueOf(timestamp ));
    } else {
      this.timestamp = Long.valueOf(timestampString);
    }
    setHeaders(headers);
  }
 
Example #6
Source File: TestJulianChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(LONDON);
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Locale.setDefault(Locale.UK);
}
 
Example #7
Source File: TestJulianChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example #8
Source File: RssFeedFactoryTest.java    From mamute with Apache License 2.0 5 votes vote down vote up
@Test
public void should_generate_feed() throws IOException {
	DefaultEnvironment env = new DefaultEnvironment(new EnvironmentType("mamute"));
	QuestionRssEntryFactory factory = new QuestionRssEntryFactory(env);
	RssFeedFactory rssFeedFactory = new RssFeedFactory(env, factory);
	
	QuestionBuilder builder = new QuestionBuilder();
	
	DateTimeUtils.setCurrentMillisFixed(100);
	User user1 = user("author1", "author@email");
	user1.setPhotoUri(new URL("http://imagemsuser1.com"));
	Question question1 = builder.withAuthor(user1)
		.withTitle("first question")
		.withDescription("question")
		.withId(1l)
		.build();
	
	User user2 = user("author2", "author@email");
	user2.setPhotoUri(new URL("http://imagemsuser2.com"));
	Question question2 = builder.withId(2l)
		.withTitle("second question")
		.withAuthor(user2)
		.build();
	
	ByteArrayOutputStream output = new ByteArrayOutputStream();
	rssFeedFactory.build(Arrays.<RssContent>asList(question1, question2), output, "title", "description");
	output.close();
	String xml = new String(output.toByteArray());
	assertTrue(xml.contains("first question"));
	assertTrue(xml.contains("second question"));
	assertTrue(xml.contains("http://imagemsuser1.com"));
	assertTrue(xml.contains("http://imagemsuser2.com"));
	DateTimeUtils.setCurrentMillisSystem();
}
 
Example #9
Source File: TestISODateTimeFormat.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example #10
Source File: TestGJChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example #11
Source File: AWSCodePipelineJobCredentialsProviderTest.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    DateTimeUtils.setCurrentMillisFixed(0L);

    when(codePipelineClient.getJobDetails(any(GetJobDetailsRequest.class))).thenReturn(getJobDetailsResult);
    when(getJobDetailsResult.getJobDetails()).thenReturn(jobDetails);
    when(jobDetails.getData()).thenReturn(jobData);
    when(jobData.getArtifactCredentials()).thenReturn(JOB_CREDENTIALS);

    credentialsProvider = new AWSCodePipelineJobCredentialsProvider(JOB_ID, codePipelineClient);
}
 
Example #12
Source File: TestIslamicChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(LONDON);
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Locale.setDefault(Locale.UK);
}
 
Example #13
Source File: TestJulianChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example #14
Source File: TransportSQLActionClassLifecycleTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void selectCurrentTimestamp() throws Exception {
    long before = DateTimeUtils.currentTimeMillis();
    SQLResponse response = execute("select current_timestamp from sys.cluster");
    long after = DateTimeUtils.currentTimeMillis();
    assertThat(response.cols(), arrayContaining("current_timestamp(3)"));
    assertThat((long) response.rows()[0][0], allOf(greaterThanOrEqualTo(before), lessThanOrEqualTo(after)));
}
 
Example #15
Source File: BasePeriod.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new period based on another using the {@link ConverterManager}.
 *
 * @param period  the period to convert
 * @param type  which set of fields this period supports, null means use type from object
 * @param chrono  the chronology to use, null means ISO default
 * @throws IllegalArgumentException if period is invalid
 * @throws IllegalArgumentException if an unsupported field's value is non-zero
 */
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
    super();
    PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
    type = (type == null ? converter.getPeriodType(period) : type);
    type = checkPeriodType(type);
    iType = type;
    if (this instanceof ReadWritablePeriod) {
        iValues = new int[size()];
        chrono = DateTimeUtils.getChronology(chrono);
        converter.setInto((ReadWritablePeriod) this, period, chrono);
    } else {
        iValues = new MutablePeriod(period, type, chrono).getValues();
    }
}
 
Example #16
Source File: Cardumen_0073_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Determines the correct chronology to use.
 *
 * @param chrono  the proposed chronology
 * @return the actual chronology
 */
private Chronology selectChronology(Chronology chrono) {
    chrono = DateTimeUtils.getChronology(chrono);
    if (iChrono != null) {
        chrono = iChrono;
    }
    if (iZone != null) {
        chrono = chrono.withZone(iZone);
    }
    return chrono;
}
 
Example #17
Source File: TestDateUtils.java    From joda-time-android with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    // Init zone info
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    JodaTimeAndroid.init(context);

    // Force the system into 24-hour time for tests
    ContentResolver cr = context.getContentResolver();
    mOldTime1224Setting = Settings.System.getString(cr, Settings.System.TIME_12_24);
    Settings.System.putString(cr, Settings.System.TIME_12_24, "24");

    // Force all tests to be in the US locale; that way we can test output in consistent manner
    Application app = (Application) ApplicationProvider.getApplicationContext();
    Resources res = app.getBaseContext().getResources();
    Configuration config = res.getConfiguration();
    Locale.setDefault(Locale.US);
    config.locale = Locale.US;
    res.updateConfiguration(config, res.getDisplayMetrics());

    // Force the default timezone
    mDefaultJodaTz = DateTimeZone.forID("America/New_York");
    mOldDefaultJodaTz = DateTimeZone.getDefault();
    DateTimeZone.setDefault(mDefaultJodaTz);

    // ...And for the system as well
    mDefaultSystemTz = TimeZone.getTimeZone("America/Chicago");
    mOldDefaultSystemTz = TimeZone.getDefault();
    TimeZone.setDefault(mDefaultSystemTz);

    // Force current "now" time, so all tests can be consistent
    mNow = new DateTime(YEAR, MONTH_OF_YEAR, DAY_OF_MONTH, HOUR_OF_DAY,
        MINUTE_OF_HOUR, SECOND_OF_MINUTE, MILLIS_OF_SECOND, mDefaultJodaTz);
    DateTimeUtils.setCurrentMillisFixed(mNow.getMillis());
}
 
Example #18
Source File: Nopol2017_0091_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Constructs a bucket, with the option of specifying the pivot year for
 * two-digit year parsing.
 *
 * @param instantLocal  the initial millis from 1970-01-01T00:00:00, local time
 * @param chrono  the chronology to use
 * @param locale  the locale to use
 * @param pivotYear  the pivot year to use when parsing two-digit years
 * @since 2.0
 */
public DateTimeParserBucket(long instantLocal, Chronology chrono,
        Locale locale, Integer pivotYear, int defaultYear) {
    super();
    chrono = DateTimeUtils.getChronology(chrono);
    iMillis = instantLocal;
    iZone = chrono.getZone();
    iChrono = chrono.withUTC();
    iLocale = (locale == null ? Locale.getDefault() : locale);
    iPivotYear = pivotYear;
    iDefaultYear = defaultYear;
}
 
Example #19
Source File: Cardumen_0073_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Determines the correct chronology to use.
 *
 * @param chrono  the proposed chronology
 * @return the actual chronology
 */
private Chronology selectChronology(Chronology chrono) {
    chrono = DateTimeUtils.getChronology(chrono);
    if (iChrono != null) {
        chrono = iChrono;
    }
    if (iZone != null) {
        chrono = chrono.withZone(iZone);
    }
    return chrono;
}
 
Example #20
Source File: TestDateTimeFormatter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(LONDON);
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Locale.setDefault(Locale.UK);
    f = new DateTimeFormatterBuilder()
            .appendDayOfWeekShortText()
            .appendLiteral(' ')
            .append(ISODateTimeFormat.dateTimeNoMillis())
            .toFormatter();
    g = ISODateTimeFormat.dateTimeNoMillis();
}
 
Example #21
Source File: TestBuddhistChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(LONDON);
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Locale.setDefault(Locale.UK);
}
 
Example #22
Source File: TestNullConverter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(DateTimeZone.forID("Europe/London"));
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Locale.setDefault(Locale.UK);
    
    ISO = ISOChronology.getInstance();
    JULIAN = JulianChronology.getInstance();
}
 
Example #23
Source File: TestDateTimeFormatStyle.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(LONDON);
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Locale.setDefault(UK);
}
 
Example #24
Source File: BaseInterval.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs an interval from a start and end instant.
 * 
 * @param start  start of this interval, null means now
 * @param end  end of this interval, null means now
 * @throws IllegalArgumentException if the end is before the start
 */
protected BaseInterval(ReadableInstant start, ReadableInstant end) {
    super();
    if (start == null && end == null) {
        iStartMillis = iEndMillis = DateTimeUtils.currentTimeMillis();
        iChronology = ISOChronology.getInstance();
    } else {
        iChronology = DateTimeUtils.getInstantChronology(start);
        iStartMillis = DateTimeUtils.getInstantMillis(start);
        iEndMillis = DateTimeUtils.getInstantMillis(end);
        checkInterval(iStartMillis, iEndMillis);
    }
}
 
Example #25
Source File: LegacyHdfsToCQL.java    From hdfs2cass with Apache License 2.0 5 votes vote down vote up
/**
* CQL-based import requires us to provide list of values we want to insert (it it's
* smart enough to figure everything else automatically). So, we convert each input
* row into a list of values, and wrap all of them in CQLRecord.
*
* @param inputRow byte representation of the input row as it was read from Avro file
* @return wraps the record into something that blends nicely into Crunch
*/
 @Override
 public CQLRecord map(ByteBuffer inputRow) {
   LegacyInputFormat row = LegacyInputFormat.parse(inputRow);
   long ts = Objects.firstNonNull(row.getTimestamp(), DateTimeUtils.currentTimeMillis());
   int ttl = Objects.firstNonNull(row.getTtl(), 0l).intValue();
   CharSequence key = row.getRowkey();
   List values = Lists.newArrayList(key, row.getColname(), row.getColval());
   return CQLRecord.create(key, ts, ttl, values);
 }
 
Example #26
Source File: TestPeriodFormatParsing.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example #27
Source File: TestGregorianChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example #28
Source File: BasePeriod.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new period based on another using the {@link ConverterManager}.
 *
 * @param period  the period to convert
 * @param type  which set of fields this period supports, null means use type from object
 * @param chrono  the chronology to use, null means ISO default
 * @throws IllegalArgumentException if period is invalid
 * @throws IllegalArgumentException if an unsupported field's value is non-zero
 */
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
    super();
    PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
    type = (type == null ? converter.getPeriodType(period) : type);
    type = checkPeriodType(type);
    iType = type;
    if (this instanceof ReadWritablePeriod) {
        iValues = new int[size()];
        chrono = DateTimeUtils.getChronology(chrono);
        converter.setInto((ReadWritablePeriod) this, period, chrono);
    } else {
        iValues = new MutablePeriod(period, type, chrono).getValues();
    }
}
 
Example #29
Source File: BaseDuration.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a duration from the given interval endpoints.
 *
 * @param start  interval start, null means now
 * @param end  interval end, null means now
 * @throws ArithmeticException if the duration exceeds a 64-bit long
 */
protected BaseDuration(ReadableInstant start, ReadableInstant end) {
    super();
    if (start == end) {
        iMillis = 0L;
    } else {
        long startMillis = DateTimeUtils.getInstantMillis(start);
        long endMillis = DateTimeUtils.getInstantMillis(end);
        iMillis = FieldUtils.safeAdd(endMillis, -startMillis);
    }
}
 
Example #30
Source File: Time_22_BasePeriod_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Creates a period from the given interval endpoints.
 *
 * @param startInstant  interval start, null means now
 * @param endInstant  interval end, null means now
 * @param type  which set of fields this period supports, null means standard
 * @throws IllegalArgumentException if period type is invalid
 */
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
    super();
    type = checkPeriodType(type);
    if (startInstant == null && endInstant == null) {
        iType = type;
        iValues = new int[size()];
    } else {
        long startMillis = DateTimeUtils.getInstantMillis(startInstant);
        long endMillis = DateTimeUtils.getInstantMillis(endInstant);
        Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
        iType = type;
        iValues = chrono.get(this, startMillis, endMillis);
    }
}