Java Code Examples for java.text.DateFormat#setCalendar()

The following examples show how to use java.text.DateFormat#setCalendar() . 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: DateTimeUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a string using {@link SimpleDateFormat} and a given pattern. This
 * method parses a string at the specified parse position and if successful,
 * updates the parse position to the index after the last character used.
 * The parsing is strict and requires months to be less than 12, days to be
 * less than 31, etc.
 *
 * @param s       string to be parsed
 * @param dateFormat Date format
 * @param tz      time zone in which to interpret string. Defaults to the Java
 *                default time zone
 * @param pp      position to start parsing from
 * @return a Calendar initialized with the parsed value, or null if parsing
 * failed. If returned, the Calendar is configured to the GMT time zone.
 */
private static Calendar parseDateFormat(String s, DateFormat dateFormat,
										TimeZone tz, ParsePosition pp) {
	if (tz == null) {
		tz = DEFAULT_ZONE;
	}
	Calendar ret = Calendar.getInstance(tz, Locale.ROOT);
	dateFormat.setCalendar(ret);
	dateFormat.setLenient(false);

	final Date d = dateFormat.parse(s, pp);
	if (null == d) {
		return null;
	}
	ret.setTime(d);
	ret.setTimeZone(UTC_ZONE);
	return ret;
}
 
Example 2
Source File: DateTimeUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a string using {@link SimpleDateFormat} and a given pattern. This
 * method parses a string at the specified parse position and if successful,
 * updates the parse position to the index after the last character used.
 * The parsing is strict and requires months to be less than 12, days to be
 * less than 31, etc.
 *
 * @param s       string to be parsed
 * @param dateFormat Date format
 * @param tz      time zone in which to interpret string. Defaults to the Java
 *                default time zone
 * @param pp      position to start parsing from
 * @return a Calendar initialized with the parsed value, or null if parsing
 * failed. If returned, the Calendar is configured to the GMT time zone.
 */
private static Calendar parseDateFormat(String s, DateFormat dateFormat,
										TimeZone tz, ParsePosition pp) {
	if (tz == null) {
		tz = DEFAULT_ZONE;
	}
	Calendar ret = Calendar.getInstance(tz, Locale.ROOT);
	dateFormat.setCalendar(ret);
	dateFormat.setLenient(false);

	final Date d = dateFormat.parse(s, pp);
	if (null == d) {
		return null;
	}
	ret.setTime(d);
	ret.setTimeZone(UTC_ZONE);
	return ret;
}
 
Example 3
Source File: DateTimeUtils.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a string using {@link SimpleDateFormat} and a given pattern. This
 * method parses a string at the specified parse position and if successful,
 * updates the parse position to the index after the last character used.
 * The parsing is strict and requires months to be less than 12, days to be
 * less than 31, etc.
 *
 * @param s       string to be parsed
 * @param dateFormat Date format
 * @param tz      time zone in which to interpret string. Defaults to the Java
 *                default time zone
 * @param pp      position to start parsing from
 * @return a Calendar initialized with the parsed value, or null if parsing
 * failed. If returned, the Calendar is configured to the GMT time zone.
 */
private static Calendar parseDateFormat(String s, DateFormat dateFormat,
    TimeZone tz, ParsePosition pp) {
  if (tz == null) {
    tz = DEFAULT_ZONE;
  }
  Calendar ret = Calendar.getInstance(tz, Locale.ROOT);
  dateFormat.setCalendar(ret);
  dateFormat.setLenient(false);

  final Date d = dateFormat.parse(s, pp);
  if (null == d) {
    return null;
  }
  ret.setTime(d);
  ret.setTimeZone(UTC_ZONE);
  return ret;
}
 
Example 4
Source File: DateTimeUtils.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a string using {@link SimpleDateFormat} and a given pattern. This
 * method parses a string at the specified parse position and if successful,
 * updates the parse position to the index after the last character used.
 * The parsing is strict and requires months to be less than 12, days to be
 * less than 31, etc.
 *
 * @param s       string to be parsed
 * @param dateFormat Date format
 * @param tz      time zone in which to interpret string. Defaults to the Java
 *                default time zone
 * @param pp      position to start parsing from
 * @return a Calendar initialized with the parsed value, or null if parsing
 * failed. If returned, the Calendar is configured to the GMT time zone.
 */
private static Calendar parseDateFormat(String s, DateFormat dateFormat,
    TimeZone tz, ParsePosition pp) {
  if (tz == null) {
    tz = DEFAULT_ZONE;
  }
  Calendar ret = Calendar.getInstance(tz, Locale.ROOT);
  dateFormat.setCalendar(ret);
  dateFormat.setLenient(false);

  final Date d = dateFormat.parse(s, pp);
  if (null == d) {
    return null;
  }
  ret.setTime(d);
  ret.setTimeZone(UTC_ZONE);
  return ret;
}
 
Example 5
Source File: CalendarRegression.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Week of year is wrong at the start and end of the year.
 */
public void Test4197699() {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setFirstDayOfWeek(MONDAY);
    cal.setMinimalDaysInFirstWeek(4);
    DateFormat fmt = new SimpleDateFormat("E dd MMM yyyy  'DOY='D 'WOY='w");
    fmt.setCalendar(cal);

    int[] DATA = {
        2000, JANUARY, 1, 52,
        2001, DECEMBER, 31, 1};

    for (int i = 0; i < DATA.length;) {
        cal.set(DATA[i++], DATA[i++], DATA[i++]);
        int expWOY = DATA[i++];
        int actWOY = cal.get(WEEK_OF_YEAR);
        if (expWOY == actWOY) {
            logln("Ok: " + fmt.format(cal.getTime()));
        } else {
            errln("FAIL: " + fmt.format(cal.getTime())
                    + ", expected WOY=" + expWOY);
            cal.add(DATE, -8);
            for (int j = 0; j < 14; ++j) {
                cal.add(DATE, 1);
                logln(fmt.format(cal.getTime()));
            }
        }
    }
}
 
Example 6
Source File: DateTimeUtil.java    From PE-HFT-Java with GNU General Public License v3.0 5 votes vote down vote up
public static String[] POSIXTimeToDateStr(long [] timesMills, DateFormat dateFormat) {
	Calendar dataBaseTime = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
	dateFormat.setCalendar(dataBaseTime);
	String []  datesStr = new String[timesMills.length];		
	for (int i = 0; i < timesMills.length; i ++ ) {
		dataBaseTime.setTimeInMillis(timesMills[i]);
		datesStr[i] = dateFormat.format(dataBaseTime.getTime());
	}
	return datesStr;
}
 
Example 7
Source File: Baby.java    From cerner_interview with MIT License 5 votes vote down vote up
public String convertoTimeZone(String continent, String city){
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(this.birth);

    DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");

    formatter.setCalendar(calendar);
    formatter.setTimeZone(TimeZone.getTimeZone(continent + "/" + city ));

    return formatter.format(calendar.getTime());
}
 
Example 8
Source File: JapaneseLenientEraTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="lenientEra")
public void testLenientEra(String lenient, String strict) throws Exception {
    Calendar c = new Calendar.Builder()
        .setCalendarType("japanese")
        .build();
    DateFormat df = new SimpleDateFormat("GGGG y-M-d", Locale.ROOT);
    df.setCalendar(c);
    Date lenDate = df.parse(lenient + "-01-01");
    df.setLenient(false);
    Date strDate = df.parse(strict + "-01-01");
    assertEquals(lenDate, strDate);
}
 
Example 9
Source File: SFFormatterTest.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to extract the date from the log record
 *
 * @param string log record representation
 * @return a date specified by the log record
 * @throws ParseException Will be thrown if parsing fails
 */
private Date extractDate(String string) throws ParseException
{
  DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  df.setCalendar(cal);
  Date date = df.parse(string);
  return date;
}
 
Example 10
Source File: JapaneseLenientEraTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="lenientEra")
public void testLenientEra(String lenient, String strict) throws Exception {
    Calendar c = new Calendar.Builder()
        .setCalendarType("japanese")
        .build();
    DateFormat df = new SimpleDateFormat("GGGG y-M-d", Locale.ROOT);
    df.setCalendar(c);
    Date lenDate = df.parse(lenient + "-01-01");
    df.setLenient(false);
    Date strDate = df.parse(strict + "-01-01");
    assertEquals(lenDate, strDate);
}
 
Example 11
Source File: AbemaLiveService.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public URI getLiveVideoInfoUrl(ChannelInfo channelInfo) throws Exception {
    String channelUrl = channelInfo.getChannelUrl();
    Matcher matcher = channelPattern.matcher(channelUrl);
    if (matcher.find()) {
        String channelId = matcher.group(1);
        String slotId = matcher.group(2);
        Map<String, String> requestProperties = new HashMap<>();
        requestProperties.put("Authorization", "bearer " + bearer);
        String slotInfo = HttpRequestUtil.downloadUrl(new URI("https://api.abema.io/v1/media/slots/" + slotId), channelInfo != null ? channelInfo.getCookies() : null, requestProperties, StandardCharsets.UTF_8);
        JSONObject slotInfoObj = JSON.parseObject(slotInfo);
        String seriesId = slotInfoObj.getJSONObject("slot").getJSONArray("programs").getJSONObject(0).getJSONObject("series").getString("id");
        Calendar japanCalendar = Calendar.getInstance(TimeZone.getTimeZone("JST"));
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        dateFormat.setCalendar(japanCalendar);
        long currentTimeMillis = System.currentTimeMillis();
        String formattedDate = dateFormat.format(currentTimeMillis);
        String timetableInfo = HttpRequestUtil.downloadUrl(new URI(String.format("https://api.abema.io/v1/media?dateFrom=%s&dateTo=%s&channelIds=%s", formattedDate, formattedDate, channelId)), channelInfo != null ? channelInfo.getCookies() : null, requestProperties, StandardCharsets.UTF_8);
        JSONArray channelSchedules = JSON.parseObject(timetableInfo).getJSONArray("channelSchedules");
        if (channelSchedules.isEmpty()) {
            return null;
        }
        JSONArray channelSlots = channelSchedules.getJSONObject(0).getJSONArray("slots");
        for (int i = 0; i < channelSlots.size(); i++) {
            JSONObject channelSlot = channelSlots.getJSONObject(i);
            if (channelSlot.getJSONArray("programs").getJSONObject(0).getJSONObject("series").getString("id").equals(seriesId)) {
                long startAt = channelSlot.getLongValue("startAt") * 1000;
                long endAt = channelSlot.getLongValue("endAt") * 1000;
                // 在节目播出时间内
                if (currentTimeMillis > startAt && currentTimeMillis < endAt) {
                    channelInfo.setStartAt(startAt);
                    channelInfo.setEndAt(endAt);
                    return new URI(NOW_ON_AIR_URL + channelId);
                }
            }
        }
    }
    return null;
}
 
Example 12
Source File: JapaneseLenientEraTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="lenientEra")
public void testLenientEra(String lenient, String strict) throws Exception {
    Calendar c = new Calendar.Builder()
        .setCalendarType("japanese")
        .build();
    DateFormat df = new SimpleDateFormat("GGGG y-M-d", Locale.ROOT);
    df.setCalendar(c);
    Date lenDate = df.parse(lenient + "-01-01");
    df.setLenient(false);
    Date strDate = df.parse(strict + "-01-01");
    assertEquals(lenDate, strDate);
}
 
Example 13
Source File: PlaceMonitorNotifications.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private String getLocalTime(SubsystemContext<PlaceMonitorSubsystemModel> context, Date time)
{
   Calendar localTime = context.getLocalTime();
   if(localTime != null) {
      DateFormat formatter = DateFormat.getDateTimeInstance();
      formatter.setCalendar(localTime);
      return formatter.format(time);
   }else{
      return DateFormat.getDateTimeInstance().format(time);
   }
}
 
Example 14
Source File: JapaneseLenientEraTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="lenientEra")
public void testLenientEra(String lenient, String strict) throws Exception {
    Calendar c = new Calendar.Builder()
        .setCalendarType("japanese")
        .build();
    DateFormat df = new SimpleDateFormat("GGGG y-M-d", Locale.ROOT);
    df.setCalendar(c);
    Date lenDate = df.parse(lenient + "-01-01");
    df.setLenient(false);
    Date strDate = df.parse(strict + "-01-01");
    assertEquals(lenDate, strDate);
}
 
Example 15
Source File: DateFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.text.DateFormat#setCalendar(java.util.Calendar)
 */
public void test_setCalendarLjava_util_Calendar() {
	DateFormat format = DateFormat.getInstance();
	Calendar cal = Calendar.getInstance();
	format.setCalendar(cal);
	assertTrue("Not identical Calendar", cal == format.getCalendar());
}
 
Example 16
Source File: CalendarRegression.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Calendar.getActualMaximum(YEAR) works wrong.
 *
 * Note: Before 1.5, this test case assumed that
 * setGregorianChange didn't change object's date. But it was
 * changed. See 4928615.
 */
public void Test4167060() {
    int field = YEAR;
    DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy G",
            Locale.US);

    int[][] dates = {
        // year, month, day of month
        {100, NOVEMBER, 1},
        {-99 /*100BC*/, JANUARY, 1},
        {1996, FEBRUARY, 29}};

    String[] id = {"Hybrid", "Gregorian", "Julian"};

    for (int k = 0; k < 3; ++k) {
        logln("--- " + id[k] + " ---");

        for (int j = 0; j < dates.length; ++j) {
            GregorianCalendar calendar = new GregorianCalendar();
            if (k == 1) {
                calendar.setGregorianChange(new Date(Long.MIN_VALUE));
            } else if (k == 2) {
                calendar.setGregorianChange(new Date(Long.MAX_VALUE));
            }
            calendar.set(dates[j][0], dates[j][1], dates[j][2]);
            format.setCalendar((Calendar) calendar.clone());

            Date dateBefore = calendar.getTime();

            int maxYear = calendar.getActualMaximum(field);
            logln("maxYear: " + maxYear + " for " + format.format(calendar.getTime()));
            logln("date before: " + format.format(dateBefore));

            int[] years = {2000, maxYear - 1, maxYear, maxYear + 1};

            for (int i = 0; i < years.length; i++) {
                boolean valid = years[i] <= maxYear;
                calendar.set(field, years[i]);
                Date dateAfter = calendar.getTime();
                int newYear = calendar.get(field);
                calendar.setTime(dateBefore); // restore calendar for next use

                logln(" Year " + years[i] + (valid ? " ok " : " bad")
                        + " => " + format.format(dateAfter));
                if (valid && newYear != years[i]) {
                    errln("  FAIL: " + newYear + " should be valid; date, month and time shouldn't change");
                } else if (!valid && newYear == years[i]) {
                    errln("  FAIL: " + newYear + " should be invalid");
                }
            }
        }
    }
}
 
Example 17
Source File: ApiObjectMapper.java    From components with Apache License 2.0 4 votes vote down vote up
public static DateFormat makeISODateFormat() {
    DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
    iso8601.setCalendar(cal);
    return iso8601;
}
 
Example 18
Source File: ApiObjectMapper.java    From components with Apache License 2.0 4 votes vote down vote up
public static DateFormat makeDateFormat(String format) {
    DateFormat dateFormat = new SimpleDateFormat(format);
    Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
    dateFormat.setCalendar(cal);
    return dateFormat;
}
 
Example 19
Source File: ApiObjectMapper.java    From components with Apache License 2.0 4 votes vote down vote up
public static DateFormat makeISODateFormat() {
    DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
    iso8601.setCalendar(cal);
    return iso8601;
}
 
Example 20
Source File: ApiObjectMapper.java    From components with Apache License 2.0 4 votes vote down vote up
public static DateFormat makeDateFormat(String format) {
    DateFormat dateFormat = new SimpleDateFormat(format);
    Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
    dateFormat.setCalendar(cal);
    return dateFormat;
}