java.text.SimpleDateFormat

Here are the examples of the java api class java.text.SimpleDateFormat taken from open source projects.

1. SimpleDateFormatTest#testFormattingUncommonTimeZoneAbbreviations()

Project: j2objc
Source File: SimpleDateFormatTest.java
View license
// In Honeycomb, only one Olson id was associated with CET (or any other "uncommon"
// abbreviation). This was changed after KitKat to avoid Java hacks on top of ICU data.
// ICU data only provides abbreviations for timezones in the locales where they would
// not be ambiguous to most people of that locale.
public void testFormattingUncommonTimeZoneAbbreviations() {
    String fmt = "yyyy-MM-dd HH:mm:ss.SSS z";
    String unambiguousDate = "1970-01-01 01:00:00.000 CET";
    String ambiguousDate = "1970-01-01 01:00:00.000 GMT+1";
    // The locale to use when formatting. Not every Locale renders "Europe/Berlin" as "CET". The
    // UK is one that does, the US is one that does not.
    Locale cetUnambiguousLocale = Locale.UK;
    Locale cetAmbiguousLocale = Locale.US;
    SimpleDateFormat sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
    assertEquals(unambiguousDate, sdf.format(new Date(0)));
    sdf = new SimpleDateFormat(fmt, cetUnambiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
    assertEquals(unambiguousDate, sdf.format(new Date(0)));
    sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
    assertEquals(ambiguousDate, sdf.format(new Date(0)));
    sdf = new SimpleDateFormat(fmt, cetAmbiguousLocale);
    sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
    assertEquals(ambiguousDate, sdf.format(new Date(0)));
}

2. FEConfig#load()

Project: ForgeEssentials
Source File: FEConfig.java
View license
@Override
public void load(Configuration config, boolean isReload) {
    config.addCustomCategoryComment(CONFIG_CAT, "Configure ForgeEssentials Core.");
    config.addCustomCategoryComment(CONFIG_CAT_MODULES, "Enable/disable modules here.");
    FORMAT_DATE = new SimpleDateFormat(config.get(CONFIG_CAT, "format_date", "yyyy-MM-dd", "Date-only format").getString());
    FORMAT_DATE_TIME = new SimpleDateFormat(config.get(CONFIG_CAT, "format_date_time", "dd.MM HH:mm", "Date and time format").getString());
    FORMAT_DATE_TIME_SECONDS = new SimpleDateFormat(config.get(CONFIG_CAT, "format_date_time_seconds", "dd.MM HH:mm:ss", "Date and time format with seconds").getString());
    FORMAT_TIME = new SimpleDateFormat(config.get(CONFIG_CAT, "format_time", "HH:mm", "Time-only format").getString());
    FORMAT_TIME_SECONDS = new SimpleDateFormat(config.get(CONFIG_CAT, "format_time", "HH:mm:ss", "Time-only format with seconds").getString());
    modlistLocation = config.get(CONFIG_CAT, "modlistLocation", "modlist.txt", "Specify the file where the modlist will be written to. This path is relative to the ForgeEssentials folder.").getString();
    majoritySleep = //
    config.get(//
    CONFIG_CAT_MISC, //
    "MajoritySleepThreshold", //
    50, "Once this percent of player sleeps, allow the night to pass").getInt(50) / 100.0f;
    checkSpacesInNames = //
    config.get(//
    CONFIG_CAT_MISC, //
    "CheckSpacesInNames", //
    true, "Check if a player's name contains spaces (can gum up some things in FE)").getBoolean();
}

3. DateTime#addRoundtripFormats()

View license
private static void addRoundtripFormats(final List<DateFormat> formats, final TimeZone timeZone) {
    SimpleDateFormat sdf = new SimpleDateFormat(ROUNDTRIP_FORMAT_UNIVERSAL);
    sdf.setTimeZone(getUniversalTimeZone());
    formats.add(sdf);
    sdf = new SimpleDateFormat(ROUNDTRIP_FORMAT_LOCAL);
    /*
         * don't need to .setTimeZone on this SDF since TZ is in its format
         * specifier and this SDF is used for PARSING only
         */
    formats.add(sdf);
    sdf = new SimpleDateFormat(ROUNDTRIP_FORMAT_UNSPECIFIED);
    sdf.setTimeZone(timeZone);
    formats.add(sdf);
}

4. DateTest#main()

Project: bboss
Source File: DateTest.java
View license
public static void main(String[] args) {
    Calendar gmtlocal = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
    gmtlocal.set(Calendar.YEAR, 2007);
    gmtlocal.set(Calendar.MONTH, 0);
    gmtlocal.set(Calendar.DAY_OF_MONTH, 1);
    gmtlocal.set(Calendar.HOUR_OF_DAY, 0);
    gmtlocal.set(Calendar.MINUTE, 0);
    Calendar gmt0 = new GregorianCalendar(TimeZone.getTimeZone("GMT+0"));
    gmt0.setTimeInMillis(gmtlocal.getTimeInMillis());
    System.out.println(gmt0.get(Calendar.YEAR));
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sf.setTimeZone(TimeZone.getTimeZone("GMT+12"));
    System.out.println(sf.format(gmtlocal.getTime()));
    sf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    System.out.println(sf.format(gmtlocal.getTime()));
    sf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    System.out.println(sf.format(gmtlocal.getTime()));
}

5. MisusedWeekYearPositiveCases#testConstructorWithLiteralPattern()

View license
void testConstructorWithLiteralPattern() {
    // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
    // BUG: Diagnostic contains: new SimpleDateFormat("yyyyMMdd_HHmm")
    simpleDateFormat = new SimpleDateFormat("YYYYMMdd_HHmm");
    // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd", DateFormatSymbols.getInstance())
    simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd", DateFormatSymbols.getInstance());
    // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd", Locale.getDefault());
}

6. ODateUtils#getDateBefore()

Project: framework
Source File: ODateUtils.java
View license
/**
     * Returns date before given days
     *
     * @param days days to before
     * @return string date string before days
     */
public static String getDateBefore(int days) {
    Date today = new Date();
    Calendar cal = new GregorianCalendar();
    cal.setTime(today);
    cal.add(Calendar.DAY_OF_MONTH, days * -1);
    Date date = cal.getTime();
    SimpleDateFormat gmtFormat = new SimpleDateFormat();
    gmtFormat.applyPattern("yyyy-MM-dd 00:00:00");
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    return gmtFormat.format(date);
}

7. ParseUtils#parseDate()

Project: java-driver
Source File: ParseUtils.java
View license
/**
     * Parse the given string as a date, using the supplied date pattern.
     * <p/>
     * This method is adapted from Apache Commons [email protected] DateUtils.parseStrictly()} method (that is used Cassandra side
     * to parse date strings)..
     *
     * @throws ParseException If the given string cannot be parsed with the given pattern.
     * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">'Working with timestamps' section of CQL specification</a>
     */
public static Date parseDate(String str, String pattern) throws ParseException {
    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(false);
    // set a default timezone for patterns that do not provide one
    parser.setTimeZone(TimeZone.getTimeZone("UTC"));
    // Java 6 has very limited support for ISO-8601 time zone formats,
    // so we need to transform the string first
    // so that accepted patterns are correctly handled,
    // such as Z for UTC, or "+00:00" instead of "+0000".
    // Note: we cannot use the X letter in the pattern
    // because it has been introduced in Java 7.
    str = str.replaceAll("(\\+|\\-)(\\d\\d):(\\d\\d)$", "$1$2$3");
    str = str.replaceAll("Z$", "+0000");
    ParsePosition pos = new ParsePosition(0);
    parser.applyPattern(pattern);
    pos.setIndex(0);
    Date date = parser.parse(str, pos);
    if (date != null && pos.getIndex() == str.length()) {
        return date;
    }
    throw new ParseException("Unable to parse the date: " + str, -1);
}

8. OpenmrsUtil#getDateTimeFormat()

Project: openmrs-core
Source File: OpenmrsUtil.java
View license
/**
	 * Get the current user's datetime format Will look similar to "mm-dd-yyyy hh:mm a". Depends on
	 * user's locale.
	 * 
	 * @return a simple date format
	 * @should return a pattern with four y characters and two h characters in it
	 * @should not allow the returned SimpleDateFormat to be modified
	 * @since 1.9
	 */
public static SimpleDateFormat getDateTimeFormat(Locale locale) {
    SimpleDateFormat dateFormat;
    SimpleDateFormat timeFormat;
    dateFormat = getDateFormat(locale);
    timeFormat = getTimeFormat(locale);
    String pattern = dateFormat.toPattern() + " " + timeFormat.toPattern();
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.applyPattern(pattern);
    return sdf;
}

9. CourseSectionImpl#convertTimeToString()

Project: sakai
Source File: CourseSectionImpl.java
View license
public static final String convertTimeToString(Time time) {
    if (time == null) {
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat(CourseSectionImpl.TIME_FORMAT_DATE_TZ);
    // Time zone from user
    TimeZone userTz = timeService.getLocalTimeZone();
    sdf.setTimeZone(userTz);
    // Today at 0.00
    Calendar date = new GregorianCalendar(userTz);
    date.set(Calendar.HOUR_OF_DAY, 0);
    date.set(Calendar.MINUTE, 0);
    // Add the RawOffset of server, to write REAL TIME in STRING detached from server
    date.setTimeInMillis(date.getTimeInMillis() + time.getTime() + TimeZone.getDefault().getRawOffset());
    sdf.setCalendar(date);
    return sdf.format(date.getTime());
}

10. AbstractExpiresHeaderFilter#getHeaderValue()

View license
@Override
protected String getHeaderValue() {
    Calendar next = Calendar.getInstance();
    next.set(Calendar.HOUR_OF_DAY, expiresTime.get(Calendar.HOUR_OF_DAY));
    next.set(Calendar.MINUTE, expiresTime.get(Calendar.MINUTE));
    next.set(Calendar.SECOND, 0);
    adjustExpires(next);
    SimpleDateFormat dateFormat = new SimpleDateFormat(EXPIRES_FORMAT);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(next.getTime());
}

11. RestUtilsTest#getTimeFromDateStringTest()

Project: ambry
Source File: RestUtilsTest.java
View license
/**
   * Tests [email protected] RestUtils#getTimeFromDateString(String)}.
   */
@Test
public void getTimeFromDateStringTest() {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH);
    dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    long curTime = System.currentTimeMillis();
    Date curDate = new Date(curTime);
    String dateStr = dateFormatter.format(curDate);
    long epochTime = RestUtils.getTimeFromDateString(dateStr);
    long actualExpectedTime = (curTime / 1000L) * 1000;
    // Note http time is kept in Seconds so last three digits will be 000
    assertEquals("Time mismatch ", actualExpectedTime, epochTime);
    dateFormatter = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.CHINA);
    curTime = System.currentTimeMillis();
    curDate = new Date(curTime);
    dateStr = dateFormatter.format(curDate);
    // any other locale is not accepted
    assertEquals("Should have returned null", null, RestUtils.getTimeFromDateString(dateStr));
    assertEquals("Should have returned null", null, RestUtils.getTimeFromDateString("abc"));
}

12. ReplacerAdapter#_tstamp()

Project: bnd
Source File: ReplacerAdapter.java
View license
public String _tstamp(String args[]) {
    String format = "yyyyMMddHHmm";
    long now = System.currentTimeMillis();
    TimeZone tz = TimeZone.getTimeZone("UTC");
    if (args.length > 1) {
        format = args[1];
    }
    if (args.length > 2) {
        tz = TimeZone.getTimeZone(args[2]);
    }
    if (args.length > 3) {
        now = Long.parseLong(args[3]);
    }
    if (args.length > 4) {
        reporter.warning("Too many arguments for tstamp: %s", Arrays.toString(args));
    }
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setTimeZone(tz);
    return sdf.format(new Date(now));
}

13. DateTimeUtils#parseDateFormat()

Project: calcite
Source File: DateTimeUtils.java
View license
//~ Methods ----------------------------------------------------------------
/**
   * Parses a string using [email protected] 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 pattern [email protected] SimpleDateFormat} pattern (not null)
   * @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, String pattern, TimeZone tz, ParsePosition pp) {
    assert pattern != null;
    SimpleDateFormat df = new SimpleDateFormat(pattern);
    if (tz == null) {
        tz = DEFAULT_ZONE;
    }
    Calendar ret = Calendar.getInstance(tz);
    df.setCalendar(ret);
    df.setLenient(false);
    java.util.Date d = df.parse(s, pp);
    if (null == d) {
        return null;
    }
    ret.setTime(d);
    ret.setTimeZone(GMT_ZONE);
    return ret;
}

14. Solr4QueryParser#getDateEnd()

View license
private String getDateEnd(Pair<Date, Integer> dateAndResolution) {
    Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
    cal.setTime(dateAndResolution.getFirst());
    switch(dateAndResolution.getSecond()) {
        case Calendar.YEAR:
            cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
        case Calendar.MONTH:
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        case Calendar.DAY_OF_MONTH:
            cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
        case Calendar.HOUR_OF_DAY:
            cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
        case Calendar.MINUTE:
            cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
        case Calendar.SECOND:
            cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));
        case Calendar.MILLISECOND:
        default:
    }
    SimpleDateFormat formatter = CachingDateFormat.getSolrDatetimeFormat();
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    return formatter.format(cal.getTime());
}

15. Solr4QueryParser#getDateStart()

View license
private String getDateStart(Pair<Date, Integer> dateAndResolution) {
    Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
    cal.setTime(dateAndResolution.getFirst());
    switch(dateAndResolution.getSecond()) {
        case Calendar.YEAR:
            cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
        case Calendar.MONTH:
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        case Calendar.DAY_OF_MONTH:
            cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
        case Calendar.HOUR_OF_DAY:
            cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
        case Calendar.MINUTE:
            cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
        case Calendar.SECOND:
            cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
        case Calendar.MILLISECOND:
        default:
    }
    SimpleDateFormat formatter = CachingDateFormat.getSolrDatetimeFormat();
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    return formatter.format(cal.getTime());
}

16. TimeUtils#getListTime()

Project: Dribbo
Source File: TimeUtils.java
View license
public static CharSequence getListTime(String created_at) {
    Calendar calendar = Calendar.getInstance();
    Date date = null;
    SimpleDateFormat srcDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z", Locale.US);
    SimpleDateFormat dstDateFormat = new SimpleDateFormat("MMMM dd yyyy", Locale.US);
    try {
        date = srcDateFormat.parse(created_at);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dstDateFormat.format(date);
}

17. DERGeneralizedTime#getDate()

Project: geronimo
Source File: DERGeneralizedTime.java
View license
public Date getDate() throws ParseException {
    SimpleDateFormat dateF;
    if (time.indexOf('.') == 14) {
        dateF = new SimpleDateFormat("yyyyMMddHHmmss.SSS'Z'");
    } else {
        dateF = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
    }
    dateF.setTimeZone(new SimpleTimeZone(0, "Z"));
    return dateF.parse(time);
}

18. Strings#getIsoDateTime()

Project: gpslogger
Source File: Strings.java
View license
/**
     * Given a Date object, returns an ISO 8601 date time string in UTC.
     * Example: 2010-03-23T05:17:22Z but not 2010-03-23T05:17:22+04:00
     *
     * @param dateToFormat The Date object to format.
     * @return The ISO 8601 formatted string.
     */
public static String getIsoDateTime(Date dateToFormat) {
    /**
         * This function is used in gpslogger.loggers.* and for most of them the
         * default locale should be fine, but in the case of HttpUrlLogger we
         * want machine-readable output, thus  Locale.US.
         *
         * Be wary of the default locale
         * http://developer.android.com/reference/java/util/Locale.html#default_locale
         */
    // GPX specs say that time given should be in UTC, no local time.
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    return sdf.format(dateToFormat);
}

19. DateUtilTest#testTimeOnlyDate()

View license
public void testTimeOnlyDate() throws UnrecognizedTimeZoneException {
    Date t = new Date(0L);
    SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss");
    tf.setTimeZone(DateUtil.UTC);
    assertEquals("00:00:00", tf.format(t));
    assertEquals("00:00:00", dateToISO8601UTCTimeString(t, false));
    TimeZone gmt1 = DateUtil.getTimeZone("GMT+01");
    tf.setTimeZone(gmt1);
    assertEquals("01:00:00", tf.format(t));
    assertEquals("01:00:00+01:00", dateToISO8601TimeString(t, gmt1));
}

20. ParseUtils#parseDate()

Project: java-driver
Source File: ParseUtils.java
View license
/**
     * Parse the given string as a date, using one of the accepted ISO-8601 date patterns.
     * <p/>
     * This method is adapted from Apache Commons [email protected] DateUtils.parseStrictly()} method (that is used Cassandra side
     * to parse date strings)..
     *
     * @throws ParseException If the given string is not a valid ISO-8601 date.
     * @see <a href="https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps">'Working with timestamps' section of CQL specification</a>
     */
public static Date parseDate(String str) throws ParseException {
    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(false);
    // set a default timezone for patterns that do not provide one
    parser.setTimeZone(TimeZone.getTimeZone("UTC"));
    // Java 6 has very limited support for ISO-8601 time zone formats,
    // so we need to transform the string first
    // so that accepted patterns are correctly handled,
    // such as Z for UTC, or "+00:00" instead of "+0000".
    // Note: we cannot use the X letter in the pattern
    // because it has been introduced in Java 7.
    str = str.replaceAll("(\\+|\\-)(\\d\\d):(\\d\\d)$", "$1$2$3");
    str = str.replaceAll("Z$", "+0000");
    ParsePosition pos = new ParsePosition(0);
    for (String parsePattern : iso8601Patterns) {
        parser.applyPattern(parsePattern);
        pos.setIndex(0);
        Date date = parser.parse(str, pos);
        if (date != null && pos.getIndex() == str.length()) {
            return date;
        }
    }
    throw new ParseException("Unable to parse the date: " + str, -1);
}

21. TestFunctions#test_exprSprintf_tz_exact()

Project: jena
Source File: TestFunctions.java
View license
private static void test_exprSprintf_tz_exact(String nodeStr) {
    String exprStr = "afn:sprintf('%1$tm %1$te,%1$tY', " + NodeValue.makeDateTime(nodeStr).toString() + ")";
    Expr expr = ExprUtils.parse(exprStr);
    NodeValue r = expr.eval(null, FunctionEnvBase.createTest());
    assertTrue(r.isString());
    String s = r.getString();
    // Parse the date
    String dtFormat = "yyyy-MM-dd'T'HH:mm:ssXXX";
    SimpleDateFormat sdtFormat = new SimpleDateFormat(dtFormat);
    Date dtDate = null;
    try {
        dtDate = sdtFormat.parse(nodeStr);
    } catch (ParseException e) {
        assertFalse("Cannot parse the input date string. Message:" + e.getMessage(), false);
    }
    // print the date based on the current timeZone.
    SimpleDateFormat stdFormatOut = new SimpleDateFormat("MM dd,yyyy");
    stdFormatOut.setTimeZone(TimeZone.getDefault());
    String outDate = stdFormatOut.format(dtDate);
    assertEquals(s, outDate);
}

22. PatternLayoutTestCase#test16()

Project: log4j
Source File: PatternLayoutTestCase.java
View license
/**
     * Tests explicit UTC time zone in pattern.
     * @throws Exception
     */
public void test16() throws Exception {
    final long start = new Date().getTime();
    PropertyConfigurator.configure("input/pattern/patternLayout16.properties");
    common();
    final long end = new Date().getTime();
    FileReader reader = new FileReader("output/patternLayout16.log");
    char chars[] = new char[50];
    reader.read(chars, 0, chars.length);
    reader.close();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    String utcStr = new String(chars, 0, 19);
    Date utcDate = format.parse(utcStr, new ParsePosition(0));
    assertTrue(utcDate.getTime() >= start - 1000 && utcDate.getTime() < end + 1000);
    String cstStr = new String(chars, 21, 19);
    format.setTimeZone(TimeZone.getTimeZone("GMT-6"));
    Date cstDate = format.parse(cstStr, new ParsePosition(0));
    assertFalse(cstStr.equals(utcStr));
    assertTrue(cstDate.getTime() >= start - 1000 && cstDate.getTime() < end + 1000);
}

23. MonthView#getMonthAndYearString()

View license
@NonNull
private String getMonthAndYearString() {
    Locale locale = Locale.getDefault();
    String pattern = "MMMM yyyy";
    if (Build.VERSION.SDK_INT < 18)
        pattern = getContext().getResources().getString(R.string.mdtp_date_v1_monthyear);
    else
        pattern = DateFormat.getBestDateTimePattern(locale, pattern);
    SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);
    formatter.applyLocalizedPattern(pattern);
    mStringBuilder.setLength(0);
    return formatter.format(mCalendar.getTime());
}

24. Const#decodeTime()

Project: pentaho-kettle
Source File: Const.java
View license
// Decodes a time value in specified date format and returns it as milliseconds since midnight.
public static int decodeTime(String s, String DateFormat) throws Exception {
    SimpleDateFormat f = new SimpleDateFormat(DateFormat);
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    f.setTimeZone(utcTimeZone);
    f.setLenient(false);
    ParsePosition p = new ParsePosition(0);
    Date d = f.parse(s, p);
    if (d == null) {
        throw new Exception("Invalid time value " + DateFormat + ": \"" + s + "\".");
    }
    return (int) d.getTime();
}

25. TurnitinAPIUtil#getGMTime()

Project: sakai
Source File: TurnitinAPIUtil.java
View license
public static String getGMTime() {
    // calculate function2 data
    SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance());
    dform.applyPattern("yyyyMMddHH");
    dform.setTimeZone(TimeZone.getTimeZone("GMT"));
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    String gmtime = dform.format(cal.getTime());
    gmtime += Integer.toString(((int) Math.floor((double) cal.get(Calendar.MINUTE) / 10)));
    return gmtime;
}

26. DateUtil#formatDate()

View license
/**
     * Formats the given date according to the specified pattern. The pattern
     * must conform to that used by the [email protected] SimpleDateFormat simple date
     * format} class.
     *
     * @param date
     *        The date to format.
     * @param pattern
     *        The pattern to use for formatting the date.
     * @return A formatted date string.
     *
     * @throws IllegalArgumentException
     *         If the given date pattern is invalid.
     *
     * @see SimpleDateFormat
     */
public static String formatDate(final Date date, final String pattern) {
    if (date == null) {
        throw new IllegalArgumentException("date is null");
    }
    if (pattern == null) {
        throw new IllegalArgumentException("pattern is null");
    }
    final SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
    formatter.setTimeZone(GMT);
    return formatter.format(date);
}

27. ModelFactoryImpl#convertDateToString()

Project: tuscany-sdo
Source File: ModelFactoryImpl.java
View license
/**
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   * @generated NOT
   */
public String convertDateToString(Object instanceValue) {
    if (instanceValue == null) {
        return null;
    }
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    return f.format((Date) instanceValue);
}

28. AbstractExpiresHeaderFilter#doActivate()

View license
@Override
protected void doActivate(ComponentContext context) throws Exception {
    Dictionary<?, ?> properties = context.getProperties();
    String time = PropertiesUtil.toString(properties.get(PROP_EXPIRES_TIME), null);
    if (StringUtils.isBlank(time)) {
        throw new ConfigurationException(PROP_EXPIRES_TIME, "Expires Time must be specified.");
    }
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    sdf.setLenient(false);
    try {
        Date date = sdf.parse(time);
        expiresTime.setTime(date);
    } catch (ParseException ex) {
        throw new ConfigurationException(PROP_EXPIRES_TIME, "Expires Time must be specified.");
    }
}

29. AdminBlobStorageServiceTest#getNotModifiedBlobAndVerify()

View license
/**
   * Gets the blob with blob ID [email protected] blobId} and verifies that the blob is not returned as blob is not modified
   * @param blobId the blob ID of the blob to GET.
   * @throws Exception
   */
public void getNotModifiedBlobAndVerify(String blobId) throws Exception {
    JSONObject headers = new JSONObject();
    SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date(System.currentTimeMillis());
    String dateStr = dateFormat.format(date);
    headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr);
    RestRequest restRequest = createRestRequest(RestMethod.GET, blobId, headers, null);
    MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
    doOperation(restRequest, restResponseChannel);
    assertEquals("Unexpected response status", ResponseStatus.NotModified, restResponseChannel.getStatus());
    assertTrue("No Date header", restResponseChannel.getHeader(RestUtils.Headers.DATE) != null);
    assertNull("No Last-Modified header expected", restResponseChannel.getHeader("Last-Modified"));
    assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", restResponseChannel.getHeader(RestUtils.Headers.BLOB_SIZE));
    assertNull("Content-Type should have been null", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE));
    assertEquals("No content expected as blob is not modified", 0, restResponseChannel.getResponseBody().length);
}

30. AdminSecurityServiceTest#testGetNotModifiedBlob()

Project: ambry
Source File: AdminSecurityServiceTest.java
View license
/**
   * Tests [email protected] SecurityService#processResponse(RestRequest, RestResponseChannel, BlobInfo, Callback)} for a Get blob
   * with the passed in [email protected] BlobInfo} for a not modified response
   * @param blobInfo the [email protected] BlobInfo} to be used for the [email protected] RestRequest}
   * @param ifModifiedSinceMs the value (as a date string) of the [email protected] RestUtils.Headers#IF_MODIFIED_SINCE} header.
   * @throws Exception
   */
private void testGetNotModifiedBlob(BlobInfo blobInfo, long ifModifiedSinceMs) throws Exception {
    SecurityServiceCallback callback = new SecurityServiceCallback();
    MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
    JSONObject headers = new JSONObject();
    SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date(ifModifiedSinceMs);
    String dateStr = dateFormat.format(date);
    headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr);
    RestRequest restRequest = createRestRequest(RestMethod.GET, "/abc", headers);
    securityService.processResponse(restRequest, restResponseChannel, blobInfo, callback).get();
    Assert.assertTrue("Callback should have been invoked", callback.callbackLatch.await(1, TimeUnit.SECONDS));
    Assert.assertNull("Exception should not have been thrown", callback.exception);
    if (ifModifiedSinceMs >= blobInfo.getBlobProperties().getCreationTimeInMs()) {
        Assert.assertEquals("Not modified response expected", ResponseStatus.NotModified, restResponseChannel.getStatus());
        verifyHeadersForGetBlobNotModified(restResponseChannel);
    } else {
        Assert.assertEquals("Not modified response should not be returned", ResponseStatus.Ok, restResponseChannel.getStatus());
        verifyHeadersForGetBlob(blobInfo.getBlobProperties(), restResponseChannel);
    }
}

31. AmbryBlobStorageServiceTest#getNotModifiedBlobAndVerify()

View license
/**
   * Gets the blob with blob ID [email protected] blobId} and verifies that the blob is not returned as blob is not modified
   * @param blobId the blob ID of the blob to GET.
   * @throws Exception
   */
public void getNotModifiedBlobAndVerify(String blobId) throws Exception {
    JSONObject headers = new JSONObject();
    SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date(System.currentTimeMillis());
    String dateStr = dateFormat.format(date);
    headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr);
    RestRequest restRequest = createRestRequest(RestMethod.GET, blobId, headers, null);
    MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
    doOperation(restRequest, restResponseChannel);
    assertEquals("Unexpected response status", ResponseStatus.NotModified, restResponseChannel.getStatus());
    assertTrue("No Date header", restResponseChannel.getHeader(RestUtils.Headers.DATE) != null);
    assertNull("No Last-Modified header expected", restResponseChannel.getHeader("Last-Modified"));
    assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", restResponseChannel.getHeader(RestUtils.Headers.BLOB_SIZE));
    assertNull("Content-Type should have been null", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE));
    assertEquals("No content expected as blob is not modified", 0, restResponseChannel.getResponseBody().length);
}

32. AmbrySecurityServiceTest#testGetNotModifiedBlob()

Project: ambry
Source File: AmbrySecurityServiceTest.java
View license
/**
   * Tests [email protected] SecurityService#processResponse(RestRequest, RestResponseChannel, BlobInfo, Callback)} for a Get blob
   * with the passed in [email protected] BlobInfo} for a not modified response
   * @param blobInfo the [email protected] BlobInfo} to be used for the [email protected] RestRequest}
   * @param ifModifiedSinceMs the value (as a date string) of the [email protected] RestUtils.Headers#IF_MODIFIED_SINCE} header.
   * @throws Exception
   */
private void testGetNotModifiedBlob(BlobInfo blobInfo, long ifModifiedSinceMs) throws Exception {
    SecurityServiceCallback callback = new SecurityServiceCallback();
    MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
    JSONObject headers = new JSONObject();
    SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date(ifModifiedSinceMs);
    String dateStr = dateFormat.format(date);
    headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr);
    RestRequest restRequest = createRestRequest(RestMethod.GET, "/abc", headers);
    securityService.processResponse(restRequest, restResponseChannel, blobInfo, callback).get();
    Assert.assertTrue("Callback should have been invoked", callback.callbackLatch.await(1, TimeUnit.SECONDS));
    Assert.assertNull("Exception should not have been thrown", callback.exception);
    if (ifModifiedSinceMs >= blobInfo.getBlobProperties().getCreationTimeInMs()) {
        Assert.assertEquals("Not modified response expected", ResponseStatus.NotModified, restResponseChannel.getStatus());
        verifyHeadersForGetBlobNotModified(restResponseChannel);
    } else {
        Assert.assertEquals("Not modified response should not be returned", ResponseStatus.Ok, restResponseChannel.getStatus());
        verifyHeadersForGetBlob(blobInfo.getBlobProperties(), restResponseChannel);
    }
}

33. ContentAdapter#getAdmobStatsIdForDate()

Project: andlytics
Source File: ContentAdapter.java
View license
@SuppressLint("SimpleDateFormat")
private long getAdmobStatsIdForDate(Date date, String siteId) {
    long result = -1;
    // make sure there is only one entry / day
    SimpleDateFormat dateFormatStart = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    SimpleDateFormat dateFormatEnd = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
    Cursor mCursor = context.getContentResolver().query(AdmobTable.CONTENT_URI, new String[] { AdmobTable.KEY_ROWID, AdmobTable.KEY_DATE }, AdmobTable.KEY_SITE_ID + "='" + siteId + "' and " + AdmobTable.KEY_DATE + " BETWEEN '" + dateFormatStart.format(date) + "' and '" + dateFormatEnd.format(date) + "'", null, null);
    if (mCursor != null && mCursor.moveToFirst()) {
        result = mCursor.getInt(mCursor.getColumnIndex(AdmobTable.KEY_ROWID));
    }
    mCursor.close();
    return result;
}

34. AndlyticsContentProvider#getAppStatsIdByDate()

View license
public long getAppStatsIdByDate(String packagename, Date date, SQLiteDatabase db) throws SQLException {
    long result = -1;
    // make sure there is only one entry / day
    SimpleDateFormat dateFormatStart = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    SimpleDateFormat dateFormatEnd = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
    Cursor mCursor = db.query(AppStatsTable.DATABASE_TABLE_NAME, new String[] { AppStatsTable.KEY_ROWID, AppStatsTable.KEY_STATS_REQUESTDATE }, AppStatsTable.KEY_STATS_PACKAGENAME + "='" + packagename + "' and " + AppStatsTable.KEY_STATS_REQUESTDATE + " BETWEEN '" + dateFormatStart.format(date) + "' and '" + dateFormatEnd.format(date) + "'", null, null, null, null);
    if (mCursor != null && mCursor.moveToFirst()) {
        result = mCursor.getInt(mCursor.getColumnIndex(AppStatsTable.KEY_ROWID));
    }
    mCursor.close();
    return result;
}

35. ASN1GeneralizedTime#setEncodingContent()

View license
public void setEncodingContent(BerOutputStream out) {
    SimpleDateFormat sdf = new SimpleDateFormat(GEN_PATTERN);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String temp = sdf.format(out.content);
    // cut off trailing 0s
    int nullId;
    int currLength;
    while (((nullId = temp.lastIndexOf('0', currLength = temp.length() - 1)) != -1) & (nullId == currLength)) {
        temp = temp.substring(0, nullId);
    }
    // deal with point (cut off if it is last char)
    if (temp.charAt(currLength) == '.') {
        temp = temp.substring(0, currLength);
    }
    out.content = (temp + "Z").getBytes(Charsets.UTF_8);
    out.length = ((byte[]) out.content).length;
}

36. AppCompatDatePickerDelegate#onLocaleChanged()

View license
@Override
protected void onLocaleChanged(Locale locale) {
    final TextView headerYear = mHeaderYear;
    if (headerYear == null) {
        // again later after everything has been set up.
        return;
    }
    // Update the date formatter.
    final String datePattern = DateFormatUtils.getBestDateTimePattern(locale, "EMMMd");
    mMonthDayFormat = new SimpleDateFormat(datePattern, locale);
    mYearFormat = new SimpleDateFormat("y", locale);
    // Update the header text.
    onCurrentDateChanged(false);
}

37. NettyAsyncResponseTest#testCookieParseExpires()

View license
@Test(groups = "standalone")
public void testCookieParseExpires() {
    // e.g. "Tue, 27 Oct 2015 12:54:24 GMT";
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date(System.currentTimeMillis() + 60000);
    final String cookieDef = String.format("efmembercheck=true; expires=%s; path=/; domain=.eclipse.org", sdf.format(date));
    HttpResponseHeaders responseHeaders = new HttpResponseHeaders(new DefaultHttpHeaders().add(HttpHeaders.Names.SET_COOKIE, cookieDef));
    NettyResponse response = new NettyResponse(new NettyResponseStatus(null, null, null, null), responseHeaders, null);
    List<Cookie> cookies = response.getCookies();
    assertEquals(cookies.size(), 1);
    Cookie cookie = cookies.get(0);
    assertTrue(cookie.getMaxAge() >= 58 && cookie.getMaxAge() <= 60);
}

38. HttpStaticFileServerHandler#setDateAndCacheHeaders()

View license
/**
     * Sets the Date and Cache headers for the HTTP Response
     *
     * @param response
     *            HTTP response
     * @param fileToCache
     *            file to extract content type
     */
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));
    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}

39. DateUtilsTest#formatIso8601Date()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void formatIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.formatISO8601Date(date);
    assertEquals(expected, actual);
    Date expectedDate = sdf.parse(expected);
    Date actualDate = DateUtils.parseISO8601Date(actual);
    assertEquals(expectedDate, actualDate);
}

40. DateUtilsTest#formatRfc822Date()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void formatRfc822Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.formatRFC822Date(date);
    assertEquals(expected, actual);
    Date expectedDate = sdf.parse(expected);
    Date actualDate = DateUtils.parseRFC822Date(actual);
    assertEquals(expectedDate, actualDate);
}

41. DateUtilsTest#parseIso8601Date()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void parseIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.iso8601DateFormat.print(date.getTime());
    assertEquals(formatted, alternative);
    Date expectedDate = sdf.parse(formatted);
    Date actualDate = DateUtils.parseISO8601Date(formatted);
    assertEquals(expectedDate, actualDate);
}

42. DateUtilsTest#parseIso8601Date_usingAlternativeFormat()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void parseIso8601Date_usingAlternativeFormat() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.alternateIso8601DateFormat.print(date.getTime());
    assertEquals(formatted, alternative);
    Date expectedDate = sdf.parse(formatted);
    Date actualDate = DateUtils.parseISO8601Date(formatted);
    assertEquals(expectedDate, actualDate);
}

43. DateUtilsTest#alternateIso8601DateFormat()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void alternateIso8601DateFormat() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.alternateIso8601DateFormat.print(date.getTime());
    assertEquals(expected, actual);
    Date expectedDate = sdf.parse(expected);
    DateTime actualDateTime = DateUtils.alternateIso8601DateFormat.parseDateTime(actual);
    assertEquals(expectedDate, new Date(actualDateTime.getMillis()));
}

44. DateUtilsTest#testIssue233()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void testIssue233() throws ParseException {
    // https://github.com/aws/aws-sdk-java/issues/233
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    final String edgeCase = "292278994-08-17T07:12:55.807Z";
    Date expected = sdf.parse(edgeCase);
    if (DEBUG)
        System.out.println("date: " + expected);
    String formatted = DateUtils.formatISO8601Date(expected);
    if (DEBUG)
        System.out.println("formatted: " + formatted);
    assertEquals(edgeCase, formatted);
    Date parsed = DateUtils.parseISO8601Date(edgeCase);
    if (DEBUG)
        System.out.println("parsed: " + parsed);
    assertEquals(expected, parsed);
    String reformatted = DateUtils.formatISO8601Date(parsed);
    assertEquals(edgeCase, reformatted);
}

45. DateUtilsTest#testIssueDaysDiff()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void testIssueDaysDiff() throws ParseException {
    // https://github.com/aws/aws-sdk-java/issues/233
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String edgeCase = "292278994-08-17T07:12:55.807Z";
    String testCase = "292278993-08-17T07:12:55.807Z";
    Date od = sdf.parse(edgeCase);
    Date testd = sdf.parse(testCase);
    long diff = od.getTime() - testd.getTime();
    assertTrue(diff == 365L * 24 * 60 * 60 * 1000);
}

46. SimpleTypeDateTimePopulateTest#testPopulate()

View license
// force others to implement this method
public void testPopulate() throws Exception {
    // Skip for JDK1.4
    if (System.getProperty("java.version").startsWith("1.4.")) {
        return;
    }
    Calendar calendar;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    for (int i = 0; i < values.length; i++) {
        calendar = ConverterUtil.convertToDateTime(values[i]);
        checkValue(xmlString[i], ConverterUtil.convertToString(calendar));
    }
}

47. JobCallbackManager#addDefaultHeaders()

Project: azkaban
Source File: JobCallbackManager.java
View license
private void addDefaultHeaders(List<HttpRequestBase> httpRequests) {
    if (httpRequests == null) {
        return;
    }
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    for (HttpRequestBase httpRequest : httpRequests) {
        httpRequest.addHeader(new BasicHeader("Date", gmtDateFormatter.format(new Date())));
        httpRequest.addHeader(new BasicHeader("Host", azkabanHostName));
    }
}

48. DataFormatUtil#getDate()

Project: bboss
Source File: DataFormatUtil.java
View license
public static Date getDate(String dateFormat, String date) throws ParseException {
    DataFormat dataFormatUtil = getDateformatThreadLocal();
    SimpleDateFormat temp = null;
    if (dataFormatUtil != null) {
        temp = dataFormatUtil.getSimpleDateFormat(dateFormat);
    } else {
        temp = new SimpleDateFormat(dateFormat);
    }
    return temp.parse(date);
}

49. DateTimeUtil#getXTitle()

Project: bither-android
Source File: DateTimeUtil.java
View license
public static final String getXTitle(KlineTimeType klineTimeType, Date date) {
    SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT_OF_MINUTE);
    switch(klineTimeType) {
        case ONE_MINUTE:
        case FIVE_MINUTES:
            break;
        case ONE_HOUR:
        case ONE_DAY:
            df = new SimpleDateFormat(DATE_TIME_FORMAT_OF_DAY);
            break;
        default:
            break;
    }
    return df.format(date);
}

50. StaticFileHandler#setDateAndCacheHeaders()

Project: blynk-server
Source File: StaticFileHandler.java
View license
/**
     * Sets the Date and Cache headers for the HTTP Response
     *
     * @param response
     *            HTTP response
     * @param fileToCache
     *            file to extract content type
     */
private static void setDateAndCacheHeaders(io.netty.handler.codec.http.HttpResponse response, File fileToCache) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));
    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}

51. OrderFileNameProcessor#process()

View license
@Override
public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();
    // there are better way to handle CSV files, but this is OK as an example
    String[] fields = in.getBody(String.class).split(",");
    String countrySpecificDate = fields[0];
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(countryDateFormat);
    Date date = simpleDateFormat.parse(countrySpecificDate);
    SimpleDateFormat universalDateFormat = new SimpleDateFormat(UNIVERSAL_DATE_FORMAT);
    String universalDate = universalDateFormat.format(date);
    fields[0] = universalDate;
    in.setHeader("CamelFileName", universalDate + ".csv");
    in.setBody(StringUtils.join(fields, ","));
}

52. JacksonMapper#init()

Project: cattle
Source File: JacksonMapper.java
View license
@PostConstruct
public void init() {
    SimpleModule module = new SimpleModule();
    module.setMixInAnnotation(Resource.class, ResourceMix.class);
    module.setMixInAnnotation(SchemaCollection.class, SchemaCollectionMixin.class);
    module.setMixInAnnotation(SchemaImpl.class, SchemaImplMixin.class);
    SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    mapper = new ObjectMapper();
    mapper.setDateFormat(df);
    mapper.registerModule(new JaxbAnnotationModule());
    mapper.registerModule(module);
    mapper.getFactory().configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    if (escapeForwardSlashes) {
        mapper.getFactory().setCharacterEscapes(new EscapeForwardSlash());
    }
}

53. RepoFileHandler#propfindFile()

Project: ceylon
Source File: RepoFileHandler.java
View license
private void propfindFile(File file, StringBuilder xml) throws IOException {
    String path = file.getCanonicalPath();
    path = path.substring(folder.length());
    xml.append("<response>\n");
    xml.append("  <href>/").append(path).append("</href>\n");
    xml.append("  <propstat>\n");
    xml.append("    <prop>\n");
    if (file.isDirectory())
        xml.append("      <resourcetype><collection/></resourcetype>\n");
    else
        xml.append("      <resourcetype/>\n");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    xml.append("      <getlastmodified>").append(format.format(new Date(file.lastModified()))).append("</getlastmodified>\n");
    xml.append("    </prop>\n");
    xml.append("    <status>HTTP/1.1 200 OK</status>\n");
    xml.append("  </propstat>\n");
    xml.append("</response>\n");
}

54. RepoFileHandler#propfindFile()

View license
private void propfindFile(File file, StringBuilder xml) throws IOException {
    String path = file.getCanonicalPath();
    path = path.substring(folder.length());
    xml.append("<response>\n");
    xml.append("  <href>/").append(path).append("</href>\n");
    xml.append("  <propstat>\n");
    xml.append("    <prop>\n");
    if (file.isDirectory())
        xml.append("      <resourcetype><collection/></resourcetype>\n");
    else
        xml.append("      <resourcetype/>\n");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    xml.append("      <getlastmodified>").append(format.format(new Date(file.lastModified()))).append("</getlastmodified>\n");
    xml.append("    </prop>\n");
    xml.append("    <status>HTTP/1.1 200 OK</status>\n");
    xml.append("  </propstat>\n");
    xml.append("</response>\n");
}

55. TracingControllerAndroid#startTracing()

View license
/**
     * Start profiling to a new file in the Downloads directory.
     *
     * Calls #startTracing(String, boolean, String, boolean) with a new timestamped filename.
     * @see #startTracing(String, boolean, String, boolean)
     */
public boolean startTracing(boolean showToasts, String categories, boolean recordContinuously) {
    mShowToasts = showToasts;
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        logAndToastError(mContext.getString(R.string.profiler_no_storage_toast));
        return false;
    }
    // Generate a hopefully-unique filename using the UTC timestamp.
    // (Not a huge problem if it isn't unique, we'll just append more data.)
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File file = new File(dir, "chrome-profile-results-" + formatter.format(new Date()));
    return startTracing(file.getPath(), showToasts, categories, recordContinuously);
}

56. AuthUtil#checkTimeStampWithFormat()

Project: cmb
Source File: AuthUtil.java
View license
public static void checkTimeStampWithFormat(String ts, String format) throws AuthenticationException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date timeStamp;
    try {
        timeStamp = dateFormat.parse(ts);
    } catch (ParseException ex) {
        logger.error("event=checking_timestamp timestamp=" + ts + " error_code=invalid_format", ex);
        throw new AuthenticationException(CMBErrorCodes.InvalidParameterValue, "Timestamp=" + ts + " is not valid");
    }
    Date now = new Date();
    if (now.getTime() - REQUEST_VALIDITY_PERIOD_MS < timeStamp.getTime() && now.getTime() + REQUEST_VALIDITY_PERIOD_MS > timeStamp.getTime()) {
        return;
    }
    logger.error("event=checking_timestamp timestamp=" + ts + " serverTime=" + dateFormat.format(now) + " error_code=timestamp_out_of_range");
    throw new AuthenticationException(CMBErrorCodes.RequestExpired, "Request timestamp " + ts + " must be within 900 seconds of the server time");
}

57. AuthUtil#checkExpiration()

Project: cmb
Source File: AuthUtil.java
View license
public static void checkExpiration(String expiration) throws AuthenticationException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date timeStamp;
    try {
        timeStamp = dateFormat.parse(expiration);
    } catch (ParseException e) {
        logger.error("event=checking_expiration expiration=" + expiration + " error_code=invalid_format", e);
        throw new AuthenticationException(CMBErrorCodes.InvalidParameterValue, "Expiration " + expiration + " is not valid");
    }
    Date now = new Date();
    if (now.getTime() < timeStamp.getTime()) {
        return;
    }
    logger.error("event=checking_timestamp expiration=" + expiration + " server_time=" + dateFormat.format(now) + " error_code=request_expired");
    throw new AuthenticationException(CMBErrorCodes.RequestExpired, "Request with expiration " + expiration + " already expired");
}

58. FormattingDateConvertor#getDateFormat()

Project: cocoon
Source File: FormattingDateConvertor.java
View license
private final SimpleDateFormat getDateFormat(Locale locale, Convertor.FormatCache formatCache) {
    SimpleDateFormat dateFormat = null;
    if (formatCache != null)
        dateFormat = (SimpleDateFormat) formatCache.get();
    if (dateFormat == null) {
        dateFormat = getDateFormat(locale);
        if (formatCache != null)
            formatCache.store(dateFormat);
    }
    dateFormat.setLenient(lenient);
    return dateFormat;
}

59. FastDateParserTest#validateSdfFormatFdpParseEquality()

View license
private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException {
    final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
    sdf.setTimeZone(tz);
    if (format.equals(SHORT_FORMAT)) {
        sdf.set2DigitYearStart(cs);
    }
    final String fmt = sdf.format(in);
    try {
        final Date out = fdp.parse(fmt);
        assertEquals(locale.toString() + " " + in + " " + format + " " + tz.getID(), in, out);
    } catch (final ParseException pe) {
        if (year >= 1868 || !locale.getCountry().equals("JP")) {
            throw pe;
        }
    }
}

60. DateValidator#isValid()

View license
/**
     * <p>Checks if the field is a valid date.  The pattern is used with
     * <code>java.text.SimpleDateFormat</code>.  If strict is true, then the
     * length will be checked so '2/12/1999' will not pass validation with
     * the format 'MM/dd/yyyy' because the month isn't two digits.
     * The setLenient method is set to <code>false</code> for all.</p>
     *
     * @param value The value validation is being performed on.
     * @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
     * @param strict Whether or not to have an exact match of the datePattern.
     * @return true if the date is valid.
     */
public boolean isValid(String value, String datePattern, boolean strict) {
    if (value == null || datePattern == null || datePattern.length() <= 0) {
        return false;
    }
    SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
    formatter.setLenient(false);
    try {
        formatter.parse(value);
    } catch (ParseException e) {
        return false;
    }
    if (strict && (datePattern.length() != value.length())) {
        return false;
    }
    return true;
}

61. AbstractCalendarListingWebScript#updateRepeatingStartEnd()

View license
private void updateRepeatingStartEnd(Date newStart, long duration, Map<String, Object> result) {
    Date newEnd = new Date(newStart.getTime() + duration);
    result.put(RESULT_START, ISO8601DateFormat.format(newStart));
    result.put(RESULT_END, ISO8601DateFormat.format(newEnd));
    String legacyDateFormat = "yyyy-MM-dd";
    SimpleDateFormat ldf = new SimpleDateFormat(legacyDateFormat);
    String legacyTimeFormat = "HH:mm";
    SimpleDateFormat ltf = new SimpleDateFormat(legacyTimeFormat);
    result.put("legacyDateFrom", ldf.format(newStart));
    result.put("legacyTimeFrom", ltf.format(newStart));
    result.put("legacyDateTo", ldf.format(newEnd));
    result.put("legacyTimeTo", ltf.format(newEnd));
}

62. AbstractParser#parseTimestamp()

Project: Conversations
Source File: AbstractParser.java
View license
public static long parseTimestamp(String timestamp) throws ParseException {
    timestamp = timestamp.replace("Z", "+0000");
    SimpleDateFormat dateFormat;
    long ms;
    if (timestamp.charAt(19) == '.' && timestamp.length() >= 25) {
        String millis = timestamp.substring(19, timestamp.length() - 5);
        try {
            double fractions = Double.parseDouble("0" + millis);
            ms = Math.round(1000 * fractions);
        } catch (NumberFormatException e) {
            ms = 0;
        }
    } else {
        ms = 0;
    }
    timestamp = timestamp.substring(0, 19) + timestamp.substring(timestamp.length() - 5, timestamp.length());
    dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
    return Math.min(dateFormat.parse(timestamp).getTime() + ms, System.currentTimeMillis());
}

63. DatasetFieldValueValidator#isValidDate()

View license
private boolean isValidDate(String dateString, String pattern) {
    boolean valid = true;
    Date date;
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    sdf.setLenient(false);
    try {
        dateString = dateString.trim();
        date = sdf.parse(dateString);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int era = calendar.get(Calendar.ERA);
        if (era == GregorianCalendar.AD) {
            if (year > 9999) {
                valid = false;
            }
        }
    } catch (ParseException e) {
        valid = false;
    }
    if (dateString.length() > pattern.length()) {
        valid = false;
    }
    return valid;
}

64. Asn1UtcTimeTest#testEncoding()

View license
@Test
public void testEncoding() throws Exception {
    /**
         * Cryptography for Developers -> ASN.1 UTCTIME Type
         * the encoding of July 4, 2003 at 11:33 and 28 seconds would be
         030704113328Z and be encoded as 0x17 0D 30 33 30 37 30 34 31 31 33 33 32 38 5A.
         */
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(new SimpleTimeZone(0, "Z"));
    String dateInString = "2003-07-04 11:33:28";
    Date date = sdf.parse(dateInString);
    testEncodingWith(date, "0x17 0D 30 33 30 37 30 34 31 31 33 33 32 38 5A");
}

65. StoneSerializersTest#fromTimestampString()

View license
private static Date fromTimestampString(String timestamp) {
    SimpleDateFormat df;
    if (timestamp.length() > SHORT_DATE_TIME_FORMAT.length()) {
        df = new SimpleDateFormat(LONG_DATE_TIME_FORMAT);
    } else {
        df = new SimpleDateFormat(SHORT_DATE_TIME_FORMAT);
    }
    df.setTimeZone(UTC);
    try {
        return df.parse(timestamp);
    } catch (Exception ex) {
        fail("invalid timestamp", ex);
        return null;
    }
}

66. TimeUtil#parseDate()

Project: falcon
Source File: TimeUtil.java
View license
/**
     * Converts given date from one format to another.
     *
     * @param date        input date
     * @param myFormat    input date format
     * @param userFormat  required format
     * @return date in userFormat
     */
public static String parseDate(String date, String myFormat, String userFormat) throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat(myFormat);
    SimpleDateFormat fromUser = new SimpleDateFormat(userFormat);
    String reformattedStr = "";
    try {
        reformattedStr = formatter.format(fromUser.parse(date));
        LOGGER.info(reformattedStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return reformattedStr;
}

67. ProxySaleOrderServiceImpl#getEndDate()

Project: fqms
Source File: ProxySaleOrderServiceImpl.java
View license
/**
     * ??????
     *
     * @param dates
     * @return
     */
private String getEndDate(List<String> dates) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    List<Date> dateList = new ArrayList<>();
    for (String s : dates) {
        try {
            dateList.add(simpleDateFormat.parse(s));
        } catch (ParseException e) {
            logger.error("???????????-??????");
        }
    }
    Date endDate = dateList.get(0);
    for (int i = 1; i < dateList.size(); i++) {
        if (dateList.get(i).after(endDate)) {
            endDate = dateList.get(i);
        }
    }
    return simpleDateFormat.format(endDate);
}

68. ProxySaleOrderServiceImpl#getBeginDate()

Project: fqms
Source File: ProxySaleOrderServiceImpl.java
View license
/**
     * ??????
     *
     * @param dates
     * @return
     */
private String getBeginDate(List<String> dates) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    List<Date> dateList = new ArrayList<>();
    for (String s : dates) {
        try {
            dateList.add(simpleDateFormat.parse(s));
        } catch (ParseException e) {
            logger.error("???????????-??????");
        }
    }
    Date beginDate = dateList.get(0);
    for (int i = 1; i < dateList.size(); i++) {
        if (dateList.get(i).before(beginDate)) {
            beginDate = dateList.get(i);
        }
    }
    return simpleDateFormat.format(beginDate);
}

69. RandomDatatToItemsMapper#call()

View license
@Override
public List<Item> call(RandomData randomData) {
    if (randomData.isError()) {
        throw new ApiException(100);
    }
    List<News> ganwus = randomData.results;
    List<Item> items = new ArrayList<>(ganwus.size());
    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
    SimpleDateFormat outputFormat = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
    for (News ganwu : ganwus) {
        Item item = new Item();
        try {
            Date date = inputFormat.parse(ganwu.getCreatedAt());
            item.date = outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            item.date = "unknown date";
        }
        item.setUrl(ganwu.getUrl());
        item.setWho(ganwu.getWho());
        item.setDescription(ganwu.getDesc());
        items.add(item);
    }
    return items;
}

70. DateWatermark#extractFromTimestamp()

Project: gobblin
Source File: DateWatermark.java
View license
/**
   * Convert timestamp to date (yyyymmddHHmmss to yyyymmdd)
   *
   * @param watermark value
   * @return value in date format
   */
private static synchronized Date extractFromTimestamp(String watermark) {
    final SimpleDateFormat inputFormat = new SimpleDateFormat(INPUTFORMAT);
    final SimpleDateFormat outputFormat = new SimpleDateFormat(OUTPUTFORMAT);
    Date outDate = null;
    try {
        Date date = inputFormat.parse(watermark);
        String dateStr = outputFormat.format(date);
        outDate = outputFormat.parse(dateStr);
    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
    }
    return outDate;
}

71. HourWatermark#extractFromTimestamp()

Project: gobblin
Source File: HourWatermark.java
View license
/**
   * Convert timestamp to hour (yyyymmddHHmmss to yyyymmddHH)
   *
   * @param watermark value
   * @return value in hour format
   */
private static synchronized Date extractFromTimestamp(String watermark) {
    final SimpleDateFormat inputFormat = new SimpleDateFormat(INPUTFORMAT);
    final SimpleDateFormat outputFormat = new SimpleDateFormat(OUTPUTFORMAT);
    Date outDate = null;
    try {
        Date date = inputFormat.parse(watermark);
        String dateStr = outputFormat.format(date);
        outDate = outputFormat.parse(dateStr);
    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
    }
    return outDate;
}

72. DateTimeType#getPartString()

Project: h-store
Source File: DateTimeType.java
View license
public String getPartString(Session session, Object dateTime, int part) {
    String javaPattern = "";
    switch(part) {
        case DAY_NAME:
            javaPattern = "EEEE";
            break;
        case MONTH_NAME:
            javaPattern = "MMMM";
            break;
    }
    SimpleDateFormat format = session.getSimpleDateFormatGMT();
    try {
        format.applyPattern(javaPattern);
    } catch (Exception e) {
    }
    Date date = (Date) convertSQLToJavaGMT(session, dateTime);
    return format.format(date);
}

73. FileContext#init()

Project: hadoop-20
Source File: FileContext.java
View license
public void init(String contextName, ContextFactory factory) {
    super.init(contextName, factory);
    fileName = getAttribute(FILE_NAME_PROPERTY);
    String recordDatePattern = getAttribute(RECORD_DATE_PATTERN_PROPERTY);
    if (recordDatePattern == null)
        recordDatePattern = DEFAULT_RECORD_DATE_PATTERN;
    recordDateFormat = new SimpleDateFormat(recordDatePattern);
    fileSuffixDateFormat = new SimpleDateFormat(FILE_SUFFIX_DATE_PATTERN);
    Calendar currentDate = Calendar.getInstance();
    if (fileName != null)
        file = new File(getFullFileName(currentDate));
    lastRecordDate = currentDate;
    parseAndSetPeriod(PERIOD_PROPERTY);
}

74. DatePickerDialog#getDisplayName()

View license
public static String getDisplayName(Calendar calendar, int field, int style, Locale locale) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return calendar.getDisplayName(field, style, locale);
    }
    final String pattern;
    final boolean longStyle = style == Calendar.LONG;
    switch(field) {
        case Calendar.DAY_OF_WEEK:
            pattern = longStyle ? "EEEE" : "EEE";
            break;
        case Calendar.MONTH:
            pattern = longStyle ? "MMMM" : "MMM";
            break;
        default:
            throw new RuntimeException("Field " + field + " isn't supported");
    }
    SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale);
    return formatter.format(calendar.getTime());
}

75. HttpUtils#setDateAndCacheHeaders()

Project: hydra
Source File: HttpUtils.java
View license
/**
     * Sets the Date and Cache headers for the HTTP Response
     *
     * @param response    HTTP response
     * @param fileToCache file to extract content type
     */
static void setDateAndCacheHeaders(HttpResponse response, Path fileToCache) throws IOException {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));
    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(Files.getLastModifiedTime(fileToCache).toMillis())));
}

76. LoanDisbursementDetailsIntegrationTest#formatExpectedDisbursementDate()

View license
private String formatExpectedDisbursementDate(String expectedDisbursementDate) {
    SimpleDateFormat source = new SimpleDateFormat("[yyyy, MM, dd]");
    SimpleDateFormat target = new SimpleDateFormat("dd MMMM yyyy");
    String date = null;
    try {
        date = target.format(source.parse(expectedDisbursementDate));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

77. IrcMessage#getServerTimestampAsPrettyDate()

Project: IrssiNotifier
Source File: IrcMessage.java
View license
public String getServerTimestampAsPrettyDate() {
    Calendar today = Calendar.getInstance();
    today = clearTimes(today);
    Calendar yesterday = Calendar.getInstance();
    yesterday.add(Calendar.DAY_OF_YEAR, -1);
    yesterday = clearTimes(yesterday);
    Calendar lastWeek = Calendar.getInstance();
    lastWeek.add(Calendar.DAY_OF_YEAR, -7);
    lastWeek = clearTimes(lastWeek);
    if (serverTimestamp.getTime() > today.getTimeInMillis())
        return "today";
    else if (serverTimestamp.getTime() > yesterday.getTimeInMillis())
        return "yesterday";
    else if (serverTimestamp.getTime() > lastWeek.getTimeInMillis()) {
        Locale locale = new Locale("US");
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE", locale);
        return dateFormat.format(serverTimestamp);
    }
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    return dateFormat.format(serverTimestamp);
}

78. ASN1GeneralizedTime#setEncodingContent()

Project: j2objc
Source File: ASN1GeneralizedTime.java
View license
public void setEncodingContent(BerOutputStream out) {
    SimpleDateFormat sdf = new SimpleDateFormat(GEN_PATTERN, Locale.US);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String temp = sdf.format(out.content);
    // cut off trailing 0s
    int nullId;
    int currLength;
    while (((nullId = temp.lastIndexOf('0', currLength = temp.length() - 1)) != -1) & (nullId == currLength)) {
        temp = temp.substring(0, nullId);
    }
    // deal with point (cut off if it is last char)
    if (temp.charAt(currLength) == '.') {
        temp = temp.substring(0, currLength);
    }
    out.content = (temp + "Z").getBytes(StandardCharsets.UTF_8);
    out.length = ((byte[]) out.content).length;
}

79. SimpleDateFormatTest#test2038()

Project: j2objc
Source File: SimpleDateFormatTest.java
View license
public void test2038() {
    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    assertEquals("Sun Nov 24 17:31:44 1833", format.format(new Date(((long) Integer.MIN_VALUE + Integer.MIN_VALUE) * 1000L)));
    assertEquals("Fri Dec 13 20:45:52 1901", format.format(new Date(Integer.MIN_VALUE * 1000L)));
    assertEquals("Thu Jan 01 00:00:00 1970", format.format(new Date(0L)));
    assertEquals("Tue Jan 19 03:14:07 2038", format.format(new Date(Integer.MAX_VALUE * 1000L)));
    assertEquals("Sun Feb 07 06:28:16 2106", format.format(new Date((2L + Integer.MAX_VALUE + Integer.MAX_VALUE) * 1000L)));
}

80. ByteBufferBytesTest#testDateTimes()

Project: Java-Lang
Source File: ByteBufferBytesTest.java
View license
@Test
public void testDateTimes() {
    long now = System.currentTimeMillis();
    bytes.appendDateTimeMillis(now);
    bytes.append(' ');
    bytes.appendDateMillis(now);
    bytes.append('T');
    bytes.appendTimeMillis(now % 86400000L);
    assertEquals(23 * 2 + 1, bytes.position());
    bytes.position(0);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss.SSS");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    String asStr = sdf.format(new Date(now));
    assertEquals(asStr, bytes.parseUtf8(SPACE_STOP));
    assertEquals(asStr, bytes.parseUtf8(SPACE_STOP));
}

81. DirectByteBufferBytesTest#testDateTimes()

View license
@Test
public void testDateTimes() {
    long now = System.currentTimeMillis();
    bytes.appendDateTimeMillis(now);
    bytes.append(' ');
    bytes.appendDateMillis(now);
    bytes.append('T');
    bytes.appendTimeMillis(now % 86400000L);
    assertEquals(23 * 2 + 1, bytes.position());
    bytes.position(0);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss.SSS");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    String asStr = sdf.format(new Date(now));
    assertEquals(asStr, bytes.parseUtf8(SPACE_STOP));
    assertEquals(asStr, bytes.parseUtf8(SPACE_STOP));
}

82. NativeBytesTest#testDateTimes()

Project: Java-Lang
Source File: NativeBytesTest.java
View license
@Test
public void testDateTimes() {
    long now = System.currentTimeMillis();
    bytes.appendDateTimeMillis(now);
    bytes.append(' ');
    bytes.appendDateMillis(now);
    bytes.append('T');
    bytes.appendTimeMillis(now % 86400000L);
    assertEquals(23 * 2 + 1, bytes.position());
    bytes.position(0);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss.SSS");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    String asStr = sdf.format(new Date(now));
    assertEquals(asStr, bytes.parseUtf8(SPACE_STOP));
    assertEquals(asStr, bytes.parseUtf8(SPACE_STOP));
}

83. Comment4FreshNews#compareTo()

Project: JianDan
Source File: Comment4FreshNews.java
View license
@Override
public int compareTo(Object another) {
    String anotherTimeString = ((Comment4FreshNews) another).getDate();
    String thisTimeString = getDate();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));
    try {
        Date anotherDate = simpleDateFormat.parse(anotherTimeString);
        Date thisDate = simpleDateFormat.parse(thisTimeString);
        return -thisDate.compareTo(anotherDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}

84. Commentator#compareTo()

Project: JianDan
Source File: Commentator.java
View license
@Override
public int compareTo(Object another) {
    String anotherTimeString = ((Commentator) another).getCreated_at().replace("T", " ");
    anotherTimeString = anotherTimeString.substring(0, anotherTimeString.indexOf("+"));
    String thisTimeString = getCreated_at().replace("T", " ");
    thisTimeString = thisTimeString.substring(0, thisTimeString.indexOf("+"));
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));
    try {
        Date anotherDate = simpleDateFormat.parse(anotherTimeString);
        Date thisDate = simpleDateFormat.parse(thisTimeString);
        return -thisDate.compareTo(anotherDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}

85. Comment4FreshNews#compareTo()

View license
@Override
public int compareTo(Object another) {
    String anotherTimeString = ((Comment4FreshNews) another).getDate();
    String thisTimeString = getDate();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));
    try {
        Date anotherDate = simpleDateFormat.parse(anotherTimeString);
        Date thisDate = simpleDateFormat.parse(thisTimeString);
        return -thisDate.compareTo(anotherDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}

86. Commentator#compareTo()

Project: JianDanRxJava
Source File: Commentator.java
View license
@Override
public int compareTo(@NonNull Object another) {
    String anotherTimeString = ((Commentator) another).getCreated_at().replace("T", " ");
    anotherTimeString = anotherTimeString.substring(0, anotherTimeString.indexOf("+"));
    String thisTimeString = getCreated_at().replace("T", " ");
    thisTimeString = thisTimeString.substring(0, thisTimeString.indexOf("+"));
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));
    try {
        Date anotherDate = simpleDateFormat.parse(anotherTimeString);
        Date thisDate = simpleDateFormat.parse(thisTimeString);
        return -thisDate.compareTo(anotherDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}

87. ISODate#parse()

Project: jPOS
Source File: ISODate.java
View license
/**
     * converts a string in DD/MM/YY format to a Date object
     * Warning: return null on invalid dates (prints Exception to console)
     * @param s String in DD/MM/YY recorded in timeZone
     * @param timeZone for GMT for example, use TimeZone.getTimeZone("GMT")
     *        and for Uruguay use TimeZone.getTimeZone("GMT-03:00")
     * @return parsed Date (or null)
     */
public static Date parse(String s, TimeZone timeZone) {
    Date d = null;
    SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
    df.setTimeZone(timeZone);
    try {
        d = df.parse(s);
    } catch (java.text.ParseException e) {
    }
    return d;
}

88. ISODate#parseDateTime()

Project: jPOS
Source File: ISODate.java
View license
/**
     * converts a string in DD/MM/YY HH:MM:SS format to a Date object
     * Warning: return null on invalid dates (prints Exception to console)
     * @param s string in DD/MM/YY HH:MM:SS format recorded in timeZone
     * @param timeZone for GMT for example, use TimeZone.getTimeZone("GMT")
     *        and for Uruguay use TimeZone.getTimeZone("GMT-03:00")
     * @return parsed Date (or null)
     */
public static Date parseDateTime(String s, TimeZone timeZone) {
    Date d = null;
    SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.UK);
    df.setTimeZone(timeZone);
    try {
        d = df.parse(s);
    } catch (java.text.ParseException e) {
    }
    return d;
}

89. TestPartitionerProjection#testDateFormatPartitionerProjectStrict()

Project: kite
Source File: TestPartitionerProjection.java
View license
@Test
// Not yet implemented
@Ignore
public void testDateFormatPartitionerProjectStrict() {
    FieldPartitioner<Long, String> fp = new DateFormatPartitioner("timestamp", "date", "yyyy-MM-dd");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    Predicate<String> projected = fp.projectStrict(Ranges.open(sepInstant, novInstant));
    Assert.assertEquals(Ranges.closed("2013-09-13", "2013-11-10"), projected);
}

90. CubeSegment#makeSegmentName()

Project: kylin
Source File: CubeSegment.java
View license
/**
     * @param startDate
     * @param endDate
     * @return if(startDate == 0 && endDate == 0), returns "FULL_BUILD", else
     * returns "yyyyMMddHHmmss_yyyyMMddHHmmss"
     */
public static String makeSegmentName(long startDate, long endDate, long startOffset, long endOffset) {
    if (startOffset == 0 && endOffset == 0) {
        startOffset = startDate;
        endOffset = endDate;
    }
    if (startOffset == 0 && (endOffset == 0 || endOffset == Long.MAX_VALUE)) {
        return "FULL_BUILD";
    }
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(startOffset) + "_" + dateFormat.format(endOffset);
}

91. CubingJob#initCubingJob()

Project: kylin
Source File: CubingJob.java
View license
private static CubingJob initCubingJob(CubeSegment seg, String jobType, String submitter, JobEngineConfig config) {
    KylinConfig kylinConfig = config.getConfig();
    CubeInstance cube = seg.getCubeInstance();
    List<ProjectInstance> projList = ProjectManager.getInstance(kylinConfig).findProjects(cube.getType(), cube.getName());
    if (projList == null || projList.size() == 0) {
        throw new RuntimeException("Cannot find the project containing the cube " + cube.getName() + "!!!");
    } else if (projList.size() >= 2) {
        throw new RuntimeException("Find more than one project containing the cube " + cube.getName() + ". It does't meet the uniqueness requirement!!! ");
    }
    CubingJob result = new CubingJob();
    SimpleDateFormat format = new SimpleDateFormat("z yyyy-MM-dd HH:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone(config.getTimeZone()));
    result.setDeployEnvName(kylinConfig.getDeployEnv());
    result.setProjectName(projList.get(0).getName());
    CubingExecutableUtil.setCubeName(seg.getCubeInstance().getName(), result.getParams());
    CubingExecutableUtil.setSegmentId(seg.getUuid(), result.getParams());
    result.setName(seg.getCubeInstance().getName() + " - " + seg.getName() + " - " + jobType + " - " + format.format(new Date(System.currentTimeMillis())));
    result.setSubmitter(submitter);
    result.setNotifyList(seg.getCubeInstance().getDescriptor().getNotifyList());
    return result;
}

92. BuildCubeWithEngine#testInnerJoinCubeWithSlr()

Project: kylin
Source File: BuildCubeWithEngine.java
View license
@SuppressWarnings("unused")
private // called by reflection
List<String> testInnerJoinCubeWithSlr() throws Exception {
    final String cubeName = "test_kylin_cube_with_slr_empty";
    clearSegment(cubeName);
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    long date1 = 0;
    long date2 = f.parse("2015-01-01").getTime();
    long date3 = f.parse("2022-01-01").getTime();
    List<String> result = Lists.newArrayList();
    if (fastBuildMode) {
        result.add(buildSegment(cubeName, date1, date3));
    } else {
        result.add(buildSegment(cubeName, date1, date2));
        //empty segment
        result.add(buildSegment(cubeName, date2, date3));
    }
    return result;
}

93. BuildCubeWithEngine#testInnerJoinCubeWithoutSlr()

Project: kylin
Source File: BuildCubeWithEngine.java
View license
@SuppressWarnings("unused")
private // called by reflection
List<String> testInnerJoinCubeWithoutSlr() throws Exception {
    final String cubeName = "test_kylin_cube_without_slr_empty";
    clearSegment(cubeName);
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    long date1 = 0;
    long date2 = f.parse("2013-01-01").getTime();
    long date3 = f.parse("2013-07-01").getTime();
    long date4 = f.parse("2022-01-01").getTime();
    List<String> result = Lists.newArrayList();
    if (fastBuildMode) {
        result.add(buildSegment(cubeName, date1, date4));
    } else {
        result.add(buildSegment(cubeName, date1, date2));
        result.add(buildSegment(cubeName, date2, date3));
        result.add(buildSegment(cubeName, date3, date4));
        //don't merge all segments
        result.add(mergeSegment(cubeName, date1, date3));
    }
    return result;
}

94. BuildCubeWithEngine#testLeftJoinCubeWithView()

Project: kylin
Source File: BuildCubeWithEngine.java
View license
@SuppressWarnings("unused")
private // called by reflection
List<String> testLeftJoinCubeWithView() throws Exception {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    List<String> result = Lists.newArrayList();
    final String cubeName = "test_kylin_cube_with_view_empty";
    clearSegment(cubeName);
    long date1 = cubeManager.getCube(cubeName).getDescriptor().getPartitionDateStart();
    long date4 = f.parse("2023-01-01").getTime();
    result.add(buildSegment(cubeName, date1, date4));
    return result;
}

95. BuildCubeWithEngine#testInnerJoinCubeWithView()

Project: kylin
Source File: BuildCubeWithEngine.java
View license
@SuppressWarnings("unused")
private // called by reflection
List<String> testInnerJoinCubeWithView() throws Exception {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    List<String> result = Lists.newArrayList();
    final String cubeName = "test_kylin_cube_with_view_inner_join_empty";
    clearSegment(cubeName);
    long date1 = cubeManager.getCube(cubeName).getDescriptor().getPartitionDateStart();
    long date4 = f.parse("2023-01-01").getTime();
    result.add(buildSegment(cubeName, date1, date4));
    return result;
}

96. BuildCubeWithEngine#testLeftJoinCubeWithSlr()

Project: kylin
Source File: BuildCubeWithEngine.java
View license
@SuppressWarnings("unused")
private // called by reflection
List<String> testLeftJoinCubeWithSlr() throws Exception {
    String cubeName = "test_kylin_cube_with_slr_left_join_empty";
    clearSegment(cubeName);
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    long date1 = cubeManager.getCube(cubeName).getDescriptor().getPartitionDateStart();
    long date2 = f.parse("2013-01-01").getTime();
    long date3 = f.parse("2013-07-01").getTime();
    long date4 = f.parse("2022-01-01").getTime();
    List<String> result = Lists.newArrayList();
    if (fastBuildMode) {
        result.add(buildSegment(cubeName, date1, date4));
    } else {
        result.add(buildSegment(cubeName, date1, date2));
        result.add(buildSegment(cubeName, date2, date3));
        result.add(buildSegment(cubeName, date3, date4));
        //don't merge all segments
        result.add(mergeSegment(cubeName, date1, date3));
    }
    return result;
}

97. BuildIIWithEngine#buildII()

Project: kylin
Source File: BuildIIWithEngine.java
View license
protected List<String> buildII(String iiName) throws Exception {
    clearSegment(iiName);
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    long date1 = 0;
    long date2 = f.parse("2015-01-01").getTime();
    List<String> result = Lists.newArrayList();
    result.add(buildSegment(iiName, date1, date2));
    return result;
}

98. DateUtil#convertStringToDate()

Project: linkbinder
Source File: DateUtil.java
View license
/**
     * ???????????(??????????null).
     * @param format ????
     * @param date ?????
     * @return ????
     */
public static Date convertStringToDate(String format, String date) {
    if (StringUtils.isEmpty(date)) {
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setLenient(false);
    ParsePosition pos = new ParsePosition(0);
    Date d = sdf.parse(date, pos);
    //  ????????????????????????
    if (pos.getIndex() != date.length()) {
        return null;
    }
    return d;
}

99. ProjectLogoManagerTest#testIsModified15()

View license
/**
     * projectId:???????????ifModifiedSince:??????
     */
@Test
public void testIsModified15() {
    String projectId = "test-project";
    String testFile = MockSystemConfig.CONFIG_PROJECT_LOGO_DIR + "/" + projectId + ".png";
    File f = new File(testFile);
    if (!f.exists()) {
        fail("?????????[" + testFile + "] ?????????");
        return;
    }
    MockSystemConfig.CONFIG_PROJECT_LOGO_DEFAULT = "test-default.png";
    String testFile2 = MockSystemConfig.CONFIG_PROJECT_LOGO_DIR + "/" + MockSystemConfig.CONFIG_PROJECT_LOGO_DEFAULT;
    File f2 = new File(testFile2);
    if (!f2.exists()) {
        fail("?????????[" + testFile2 + "] ?????????");
        return;
    }
    SimpleDateFormat rfc1123DateFormat = new SimpleDateFormat("E, dd MMM yyyy hh:mm:ss.000 zzz");
    rfc1123DateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String ifModifiedSince = rfc1123DateFormat.format(new Date(f.lastModified()));
    assertTrue(projectLogoManager.isModified(projectId, ifModifiedSince));
}

100. CachedDateFormatTest#test17()

Project: log4j
Source File: CachedDateFormatTest.java
View license
/**
   * Check caching when multiple SSS appear in pattern
   */
public void test17() {
    Date jul2 = new Date(12602L * 86400000L);
    String badPattern = "HH:mm:ss,SSS HH:mm:ss,SSS";
    SimpleDateFormat simpleFormat = new SimpleDateFormat(badPattern);
    simpleFormat.setTimeZone(GMT);
    DateFormat cachedFormat = new CachedDateFormat(simpleFormat, 1000);
    String s = cachedFormat.format(jul2);
    assertEquals("00:00:00,000 00:00:00,000", s);
    jul2.setTime(jul2.getTime() + 120);
    assertEquals("00:00:00,120 00:00:00,120", simpleFormat.format(jul2));
    s = cachedFormat.format(jul2);
    //
    //  TODO: why is this returning ,120 ... , 120
    //
    //assertEquals("00:00:00,120 00:00:00,000", s) ;
    int maxValid = CachedDateFormat.getMaximumCacheValidity(badPattern);
    assertEquals(1, maxValid);
}