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
File: SimpleDateFormatTest.java
// 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
File: FEConfig.java
@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()

Project: team-explorer-everywhere
File: DateTime.java
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
File: DateTest.java
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. ParseUtils#parseDate()

Project: java-driver
File: ParseUtils.java
/**
     * Parse the given string as a date, using the supplied date pattern.
     * <p/>
     * This method is adapted from Apache Commons {@code 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);
}

6. ODateUtils#getDateBefore()

Project: framework
File: ODateUtils.java
/**
     * 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. MisusedWeekYearPositiveCases#testConstructorWithLiteralPattern()

Project: error-prone
File: MisusedWeekYearPositiveCases.java
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());
}

8. CourseSectionImpl#convertTimeToString()

Project: sakai
File: CourseSectionImpl.java
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());
}

9. OpenmrsUtil#getDateTimeFormat()

Project: openmrs-core
File: OpenmrsUtil.java
/**
	 * 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;
}

10. Const#decodeTime()

Project: pentaho-kettle
File: Const.java
// 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();
}

11. TurnitinAPIUtil#getGMTime()

Project: sakai
File: TurnitinAPIUtil.java
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;
}

12. ModelFactoryImpl#convertDateToString()

Project: tuscany-sdo
File: ModelFactoryImpl.java
/**
   * <!-- 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);
}

13. DateUtil#formatDate()

Project: team-explorer-everywhere
File: DateUtil.java
/**
     * Formats the given date according to the specified pattern. The pattern
     * must conform to that used by the {@link 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);
}

14. MonthView#getMonthAndYearString()

Project: MaterialDateTimePicker
File: MonthView.java
@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());
}

15. PatternLayoutTestCase#test16()

Project: log4j
File: PatternLayoutTestCase.java
/**
     * 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);
}

16. TestFunctions#test_exprSprintf_tz_exact()

Project: jena
File: TestFunctions.java
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);
}

17. ParseUtils#parseDate()

Project: java-driver
File: ParseUtils.java
/**
     * Parse the given string as a date, using one of the accepted ISO-8601 date patterns.
     * <p/>
     * This method is adapted from Apache Commons {@code 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);
}

18. DateUtilTest#testTimeOnlyDate()

Project: incubator-freemarker
File: DateUtilTest.java
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));
}

19. DateTimeUtils#parseDateFormat()

Project: calcite
File: DateTimeUtils.java
//~ Methods ----------------------------------------------------------------
/**
   * 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 pattern {@link 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;
}

20. ReplacerAdapter#_tstamp()

Project: bnd
File: ReplacerAdapter.java
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));
}

21. AbstractExpiresHeaderFilter#getHeaderValue()

Project: acs-aem-commons
File: AbstractExpiresHeaderFilter.java
@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());
}

22. Strings#getIsoDateTime()

Project: gpslogger
File: Strings.java
/**
     * 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);
}

23. DERGeneralizedTime#getDate()

Project: geronimo
File: DERGeneralizedTime.java
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);
}

24. TimeUtils#getListTime()

Project: Dribbo
File: TimeUtils.java
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);
}

25. Solr4QueryParser#getDateStart()

Project: community-edition
File: Solr4QueryParser.java
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());
}

26. Solr4QueryParser#getDateEnd()

Project: community-edition
File: Solr4QueryParser.java
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());
}

27. RestUtilsTest#getTimeFromDateStringTest()

Project: ambry
File: RestUtilsTest.java
/**
   * Tests {@link 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"));
}

28. SublimeDatePicker#onLocaleChanged()

Project: SublimePicker
File: SublimeDatePicker.java
private void onLocaleChanged(Locale locale) {
    final TextView headerYear = mHeaderYear;
    if (headerYear == null) {
        // again later after everything has been set up.
        return;
    }
    // Update the date formatter.
    String datePattern;
    if (SUtils.isApi_18_OrHigher()) {
        datePattern = android.text.format.DateFormat.getBestDateTimePattern(locale, "EMMMd");
    } else {
        datePattern = DateTimePatternHelper.getBestDateTimePattern(locale, DateTimePatternHelper.PATTERN_EMMMd);
    }
    mMonthDayFormat = new SimpleDateFormat(datePattern, locale);
    mYearFormat = new SimpleDateFormat("y", locale);
    // Update the header text.
    onCurrentDateChanged(false);
}

29. WeekOfYear#initDateFormat()

Project: StreamCQL
File: WeekOfYear.java
private void initDateFormat() {
    if (formatter1 != null) {
        return;
    }
    formatter1 = new SimpleDateFormat(UDFConstants.TIMESTAMP_FORMAT);
    formatter2 = new SimpleDateFormat(UDFConstants.DATE_FORMAT);
    calendar = Calendar.getInstance();
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    calendar.setMinimalDaysInFirstWeek(4);
    /*
             * ????????
             */
    formatter1.setLenient(false);
    formatter2.setLenient(false);
}

30. HttpHeadersTests#getDateFromHeader()

Project: spring-android
File: HttpHeadersTests.java
// helpers
private Date getDateFromHeader(HttpHeaders headers, String key) {
    String headerDate = headers.getFirst(key);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = null;
    try {
        date = simpleDateFormat.parse(headerDate);
    } catch (ParseException e) {
    }
    return date;
}

31. SlingDateValuesTest#testDateValues()

Project: sling
File: SlingDateValuesTest.java
public void testDateValues() throws IOException {
    SimpleDateFormat ecmaFmt = new SimpleDateFormat(ECMA_FORMAT, Locale.US);
    Date now = new Date();
    Date date2 = new Date(10000042L);
    String nowStr = ecmaFmt.format(now);
    String date2Str = ecmaFmt.format(date2);
    for (SimpleDateFormat fmt : testFormats) {
        String testStr = fmt.format(now);
        String test2Str = fmt.format(date2);
        doDateTest(nowStr, testStr, date2Str, test2Str);
    }
}

32. LogFileDeleter#deleteOldLogs()

Project: secor
File: LogFileDeleter.java
public void deleteOldLogs() throws Exception {
    if (mConfig.getLocalLogDeleteAgeHours() <= 0) {
        return;
    }
    String[] consumerDirs = FileUtil.list(mConfig.getLocalPath());
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    format.setTimeZone(mConfig.getTimeZone());
    for (String consumerDir : consumerDirs) {
        long modificationTime = FileUtil.getModificationTimeMsRecursive(consumerDir);
        String modificationTimeStr = format.format(modificationTime);
        LOG.info("Consumer log dir {} last modified at {}", consumerDir, modificationTimeStr);
        final long localLogDeleteAgeMs = mConfig.getLocalLogDeleteAgeHours() * 60L * 60L * 1000L;
        if (System.currentTimeMillis() - modificationTime > localLogDeleteAgeMs) {
            LOG.info("Deleting directory {} last modified at {}", consumerDir, modificationTimeStr);
            FileUtil.delete(consumerDir);
        }
    }
}

33. JsfUtil#convertISO8601StringToCalendar()

Project: sakai
File: JsfUtil.java
/**
	 * Converts an ISO-8601 formatted string into a Calendar object
	 *
	 * @param str
	 * @return Calendar
	 */
public static Calendar convertISO8601StringToCalendar(String str) {
    if (StringUtils.trimToNull(str) == null) {
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat(JsfUtil.ISO_8601_DATE_FORMAT);
    sdf.setTimeZone(TimeService.getLocalTimeZone());
    try {
        Date date = sdf.parse(str);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    } catch (Exception e) {
        log.warn("Bad ISO 8601 date in sections: " + str);
    }
    return null;
}

34. JsfUtil#convertStringToTime()

Project: sakai
File: JsfUtil.java
/**
	 * Converts a string and a boolean (am) into a java.sql.Time object.
	 *
	 * @param str
	 * @param am
	 * @return
	 */
public static Time convertStringToTime(String str, boolean am) {
    if (StringUtils.trimToNull(str) == null) {
        return null;
    }
    // Set the am/pm flag to ensure that the time is parsed properly
    if (am) {
        str = str + " " + new DateFormatSymbols(new ResourceLoader().getLocale()).getAmPmStrings()[0];
    } else {
        str = str + " " + new DateFormatSymbols(new ResourceLoader().getLocale()).getAmPmStrings()[1];
    }
    String pattern = (str.indexOf(':') != -1) ? JsfUtil.TIME_PATTERN_LONG : JsfUtil.TIME_PATTERN_SHORT;
    SimpleDateFormat sdf = new SimpleDateFormat(pattern, new ResourceLoader().getLocale());
    sdf.setTimeZone(TimeService.getLocalTimeZone());
    Date date;
    try {
        date = sdf.parse(str);
    } catch (ParseException pe) {
        throw new RuntimeException("A bad date made it through validation!  This should never happen!");
    }
    return ConversionUtil.convertDateToTime(date, am);
}

35. Iso8601DateFormat#format()

Project: sakai
File: Iso8601DateFormat.java
/**
   * DOCUMENTATION PENDING
   *
   * @param date DOCUMENTATION PENDING
   *
   * @return DOCUMENTATION PENDING
   */
public String format(Date date) {
    log.debug("format(Date " + date + ")");
    SimpleDateFormat sdf = null;
    if (this.pattern == null) {
        sdf = new SimpleDateFormat();
    } else {
        sdf = new SimpleDateFormat(pattern);
    }
    return sdf.format(date);
}

36. podHomeBean#convertDateString()

Project: sakai
File: podHomeBean.java
/**
	 * Converts the date string input using the FORMAT_STRING given.
	 * 
	 * @param inputDate
	 *            The string that needs to be converted.
	 * @param FORMAT_STRING
	 *            The format the data needs to conform to
	 * 
	 * @return Date
	 * 			The Date object containing the date passed in or null if invalid.
	 * 
	 * @throws ParseException
	 * 			If not a valid date compared to FORMAT_STRING given
	 */
private Date convertDateString(final String inputDate, final String FORMAT_STRING) throws ParseException {
    Date convertedDate = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT_STRING, rb.getLocale());
    dateFormat.setTimeZone(TimeService.getLocalTimeZone());
    try {
        convertedDate = dateFormat.parse(inputDate);
    } catch (ParseException e) {
        dateFormat = new SimpleDateFormat(FORMAT_STRING, Locale.ENGLISH);
        dateFormat.setTimeZone(TimeService.getLocalTimeZone());
        convertedDate = dateFormat.parse(inputDate);
    }
    return convertedDate;
}

37. BlogAtomFeedsTests#containsBlogPostFields()

Project: sagan
File: BlogAtomFeedsTests.java
@Test
public void containsBlogPostFields() throws Exception {
    Post post = PostBuilder.post().category(PostCategory.ENGINEERING).isBroadcast().build();
    postRepository.save(post);
    ResultActions resultActions = mockMvc.perform(get("/blog.atom"));
    MvcResult mvcResult = resultActions.andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/atom+xml")).andReturn();
    assertThat(mvcResult.getResponse().getCharacterEncoding(), equalTo("utf-8"));
    String atomFeed = mvcResult.getResponse().getContentAsString();
    assertThat(atomFeed, containsString(post.getTitle()));
    assertThat(atomFeed, containsString(post.getRenderedContent()));
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setTimeZone(DateFactory.DEFAULT_TIME_ZONE);
    String postDate = dateFormat.format(post.getCreatedAt());
    assertThat(atomFeed, containsString(postDate));
    assertThat(atomFeed, containsString("/blog/" + post.getPublicSlug()));
    assertThat(atomFeed, containsString(PostCategory.ENGINEERING.getDisplayName()));
    assertThat(atomFeed, containsString("Broadcast"));
}

38. EndomondoSynchronizer#parseFeed()

Project: runnerup
File: EndomondoSynchronizer.java
/*
     * {"message":{"short":"was out <0>running<\/0>.", "text":"was out
     * <0>running<\/0>. He tracked 6.64 km in 28m:56s.",
     * "date":"Yesterday at 10:31", "actions":[
     * {"id":233354212,"sport":0,"type":"workout","sport2":0}],
     * "text.win":"6.64 km in 28m:56s"}, "id":200472103,
     * "order_time":"2013-08-20 08:31:52 UTC",
     * "from":{"id":6408321,"picture":5521936, "name":"Jonas Oreland"},
     * "type":"workout"},
     */
private void parseFeed(FeedUpdater feedUpdater, JSONObject reply) throws JSONException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'", Locale.getDefault());
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    JSONArray arr = reply.getJSONArray("data");
    for (int i = 0; i < arr.length(); i++) {
        JSONObject o = arr.getJSONObject(i);
        try {
            if ("workout".contentEquals(o.getString("type"))) {
                final ContentValues c = parseWorkout(df, o);
                feedUpdater.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

39. NightscoutUploader#populateV1APICalibrationEntry()

Project: xDrip
File: NightscoutUploader.java
private void populateV1APICalibrationEntry(JSONObject json, Calibration record) throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
    format.setTimeZone(TimeZone.getDefault());
    json.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
    json.put("type", "cal");
    json.put("date", record.timestamp);
    json.put("dateString", format.format(record.timestamp));
    if (record.check_in) {
        json.put("slope", (long) (record.first_slope));
        json.put("intercept", (long) ((record.first_intercept)));
        json.put("scale", record.first_scale);
    } else {
        json.put("slope", (long) (record.slope * 1000));
        json.put("intercept", (long) ((record.intercept * -1000) / (record.slope * 1000)));
        json.put("scale", 1);
    }
}

40. NightscoutUploader#populateV1APIBGEntry()

Project: xDrip
File: NightscoutUploader.java
private void populateV1APIBGEntry(JSONObject json, BgReading record) throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
    format.setTimeZone(TimeZone.getDefault());
    json.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
    json.put("date", record.timestamp);
    json.put("dateString", format.format(record.timestamp));
    json.put("sgv", (int) record.calculated_value);
    json.put("direction", record.slopeName());
    json.put("type", "sgv");
    json.put("filtered", record.filtered_data * 1000);
    json.put("unfiltered", record.age_adjusted_raw_value * 1000);
    json.put("rssi", 100);
    json.put("noise", Integer.valueOf(record.noiseValue()));
}

41. OpenOrdersJSONTest#testUnmarshal()

Project: XChange
File: OpenOrdersJSONTest.java
@Test
public void testUnmarshal() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = OpenOrdersJSONTest.class.getResourceAsStream("/trade/example-openorders.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    TaurusOrder[] orders = mapper.readValue(is, TaurusOrder[].class);
    assertThat(orders.length).isEqualTo(1);
    //    [{"amount":"0.01000000","datetime":"2015-03-25 09:31:36","id":"musi0joa54mzpj0vvpo811mr53g6cj4zewieg7plccl2wlxrbm0cnm3tqkz3343i","price":"400.00","status":"0","type":"1"}]
    // Verify that the example data was unmarshalled correctly
    assertThat(orders[0].getId()).isEqualTo("musi0joa54mzpj0vvpo811mr53g6cj4zewieg7plccl2wlxrbm0cnm3tqkz3343i");
    assertThat(orders[0].getPrice()).isEqualTo(new BigDecimal("400.00"));
    assertThat(orders[0].getAmount()).isEqualTo(new BigDecimal("0.01000000"));
    assertThat(orders[0].getType()).isEqualTo(Order.OrderType.ASK);
    assertThat(orders[0].getStatus()).isEqualTo(TaurusOrder.Status.active);
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // The json date is UTC; Paris is UTC+1.
    format.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
    assertThat(format.format(orders[0].getDatetime())).isEqualTo("2015-03-25 10:31:36");
}

42. CoinsetterPriceAlertListTest#test()

Project: XChange
File: CoinsetterPriceAlertListTest.java
@Test
public void test() throws IOException {
    CoinsetterPriceAlertList priceAlertList = ObjectMapperHelper.readValue(getClass().getResource("list.json"), CoinsetterPriceAlertList.class);
    assertEquals(2, priceAlertList.getPriceAlerts().length);
    CoinsetterPriceAlert alert = priceAlertList.getPriceAlerts()[0];
    assertEquals(new BigDecimal("800"), alert.getPrice());
    assertEquals("CROSSES", alert.getCondition());
    assertEquals(UUID.fromString("f5b02181-fb50-42ca-969f-afc20e91963a"), alert.getUuid());
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    format.setTimeZone(TimeZone.getTimeZone("EST"));
    assertEquals("2014-04-18", format.format(alert.getCreateDate()));
    assertEquals("TEXT", alert.getType());
}

43. CoinsetterNewsAlertListTest#test()

Project: XChange
File: CoinsetterNewsAlertListTest.java
@Test
public void test() throws IOException {
    CoinsetterNewsAlertList newsAlertList = ObjectMapperHelper.readValue(getClass().getResource("list.json"), CoinsetterNewsAlertList.class);
    assertEquals(3, newsAlertList.getMessageList().length);
    CoinsetterNewsAlert alert = newsAlertList.getMessageList()[0];
    assertEquals("Buy Low, Sell High", alert.getMessage());
    assertEquals(UUID.fromString("128e405c-7683-02e9-b6a3-d7bdb490526e"), alert.getUuid());
    SimpleDateFormat format = new SimpleDateFormat("EEE, MMM dd, yyyy", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("EST"));
    assertEquals("Thu, Apr 10, 2014", format.format(alert.getCreateDate()));
    assertEquals("MARKET", alert.getMessageType());
}

44. CoinsetterFinancialTransactionTest#test()

Project: XChange
File: CoinsetterFinancialTransactionTest.java
@Test
public void test() throws IOException {
    CoinsetterFinancialTransaction financialTransaction = ObjectMapperHelper.readValue(getClass().getResource("financialTransaction.json"), CoinsetterFinancialTransaction.class);
    assertEquals(UUID.fromString("ef178baa-46f0-441d-a97d-c92a848f4f29"), financialTransaction.getUuid());
    assertEquals(UUID.fromString("5ba865b8-cd46-4da5-a99a-fdf7bcbc37b3"), financialTransaction.getCustomerUuid());
    assertEquals(UUID.fromString("3b1a82ce-e632-4281-b1bd-eb9bf3aeb60c"), financialTransaction.getAccountUuid());
    assertEquals(new BigDecimal("1000.00000000"), financialTransaction.getAmount());
    assertEquals("USD", financialTransaction.getAmountDenomination());
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS");
    format.setTimeZone(TimeZone.getTimeZone("EST"));
    assertEquals("12/05/2013 11:03:31.000", format.format(financialTransaction.getCreateDate()));
    assertEquals("Unit test", financialTransaction.getReferenceNumber());
    assertEquals("Deposit description", financialTransaction.getTransactionCategoryDescription());
    assertEquals("Deposit", financialTransaction.getTransactionCategoryName());
}

45. BTCETickerJSONTest#testUnmarshal()

Project: XChange
File: BTCETickerJSONTest.java
@Test
public void testUnmarshal() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = BTCETickerJSONTest.class.getResourceAsStream("/v3/marketdata/example-ticker-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BTCETickerWrapper bTCETickerWrapper = mapper.readValue(is, BTCETickerWrapper.class);
    // Verify that the example data was unmarshalled correctly
    assertThat(bTCETickerWrapper.getTicker(BTCEAdapters.getPair(CurrencyPair.BTC_USD)).getLast()).isEqualTo(new BigDecimal("757"));
    assertThat(bTCETickerWrapper.getTicker(BTCEAdapters.getPair(CurrencyPair.BTC_USD)).getHigh()).isEqualTo(new BigDecimal("770"));
    assertThat(bTCETickerWrapper.getTicker(BTCEAdapters.getPair(CurrencyPair.BTC_USD)).getLow()).isEqualTo(new BigDecimal("655"));
    assertThat(bTCETickerWrapper.getTicker(BTCEAdapters.getPair(CurrencyPair.BTC_USD)).getVol()).isEqualTo(new BigDecimal("17512163.25736"));
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateString = f.format(DateUtils.fromMillisUtc(bTCETickerWrapper.getTicker(BTCEAdapters.getPair(CurrencyPair.BTC_USD)).getUpdated() * 1000L));
    System.out.println(dateString);
    assertThat(dateString).isEqualTo("2013-11-23 11:13:39");
}

46. BittrexUtils#toDate()

Project: XChange
File: BittrexUtils.java
public static Date toDate(String datetime) {
    // Bittrex can truncate the millisecond component of datetime fields (e.g. 2015-12-20T02:07:51.5)  
    // to the point where if the milliseconds are zero then they are not shown (e.g. 2015-12-26T09:55:23).
    SimpleDateFormat sdf;
    if (datetime.length() == 19) {
        sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    } else {
        sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    }
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
        return sdf.parse(datetime);
    } catch (ParseException e) {
        logger.warn("Unable to parse datetime={}", datetime, e);
        return EPOCH;
    }
}

47. BitstampAdapterTest#testTickerAdapter()

Project: XChange
File: BitstampAdapterTest.java
@Test
public void testTickerAdapter() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = BitstampAdapterTest.class.getResourceAsStream("/marketdata/example-ticker-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BitstampTicker bitstampTicker = mapper.readValue(is, BitstampTicker.class);
    Ticker ticker = BitstampAdapters.adaptTicker(bitstampTicker, CurrencyPair.BTC_USD);
    assertThat(ticker.getLast().toString()).isEqualTo("134.89");
    assertThat(ticker.getBid().toString()).isEqualTo("134.89");
    assertThat(ticker.getAsk().toString()).isEqualTo("134.92");
    assertThat(ticker.getVolume()).isEqualTo(new BigDecimal("21982.44926674"));
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateString = f.format(ticker.getTimestamp());
    assertThat(dateString).isEqualTo("2013-10-14 21:45:33");
}

48. BitstampAdapterTest#testOrderBookAdapter()

Project: XChange
File: BitstampAdapterTest.java
@Test
public void testOrderBookAdapter() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = BitstampAdapterTest.class.getResourceAsStream("/marketdata/example-full-depth-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BitstampOrderBook bitstampOrderBook = mapper.readValue(is, BitstampOrderBook.class);
    OrderBook orderBook = BitstampAdapters.adaptOrderBook(bitstampOrderBook, CurrencyPair.BTC_USD, 1000);
    assertThat(orderBook.getBids().size()).isEqualTo(1281);
    // verify all fields filled
    assertThat(orderBook.getBids().get(0).getLimitPrice().toString()).isEqualTo("123.09");
    assertThat(orderBook.getBids().get(0).getType()).isEqualTo(OrderType.BID);
    assertThat(orderBook.getBids().get(0).getTradableAmount()).isEqualTo(new BigDecimal("0.16248274"));
    assertThat(orderBook.getBids().get(0).getCurrencyPair()).isEqualTo(CurrencyPair.BTC_USD);
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateString = f.format(orderBook.getTimeStamp());
    assertThat(dateString).isEqualTo("2013-09-10 12:31:44");
}

49. RequestResource#evalDate()

Project: wink
File: RequestResource.java
@GET
@Path("date")
public Response evalDate(@Context Request req) {
    if (!"GET".equals(req.getMethod())) {
        throw new WebApplicationException();
    }
    if (date == null) {
        return Response.serverError().build();
    }
    System.out.println("GET Date: " + date);
    ResponseBuilder respBuilder = req.evaluatePreconditions(date);
    if (respBuilder != null) {
        System.out.println("Returning 304");
        return respBuilder.build();
    }
    System.out.println("Returning 200");
    SimpleDateFormat rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
    rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));
    return Response.ok("the date: " + rfc1123Format.format(date)).lastModified(date).build();
}

50. JacksonModule#createJacksonJsonProvider()

Project: wasabi
File: JacksonModule.java
private JacksonJsonProvider createJacksonJsonProvider() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setSerializationInclusion(ALWAYS);
    mapper.registerModule(new SimpleModule() {

        {
            addSerializer(Double.class, new NaNSerializerDouble());
            addSerializer(Float.class, new NaNSerializerFloat());
            addDeserializer(Timestamp.class, new SQLTimestampDeserializer());
            addDeserializer(Experiment.State.class, new ExperimentStateDeserializer());
            addSerializer(new UpperCaseToStringSerializer<>(Experiment.State.class));
        }
    });
    SimpleDateFormat iso8601Formatter = new SimpleDateFormat(ISO8601_DATE_FORMAT);
    iso8601Formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    mapper.setDateFormat(iso8601Formatter);
    JacksonJsonProvider provider = new WasabiJacksonJsonProvider();
    provider.setMapper(mapper);
    return provider;
}

51. DateTimeType#getPartString()

Project: voltdb
File: DateTimeType.java
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);
}

52. DateUtils#getDateFormat()

Project: uhabits
File: DateUtils.java
public static SimpleDateFormat getDateFormat(String skeleton) {
    String pattern;
    Locale locale = Locale.getDefault();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        pattern = DateFormat.getBestDateTimePattern(locale, skeleton);
    else
        pattern = skeleton;
    SimpleDateFormat format = new SimpleDateFormat(pattern, locale);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    return format;
}

53. XMLReporter#addDurationAttributes()

Project: testng
File: XMLReporter.java
/**
   * Add started-at, finished-at and duration-ms attributes to the <suite> tag
   */
public static void addDurationAttributes(XMLReporterConfig config, Properties attributes, Date minStartDate, Date maxEndDate) {
    SimpleDateFormat format = new SimpleDateFormat(config.getTimestampFormat());
    TimeZone utc = TimeZone.getTimeZone("UTC");
    format.setTimeZone(utc);
    String startTime = format.format(minStartDate);
    String endTime = format.format(maxEndDate);
    long duration = maxEndDate.getTime() - minStartDate.getTime();
    attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime);
    attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime);
    attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, Long.toString(duration));
}

54. TestVariableResolver#testFunctionNamespace1()

Project: lucene-solr
File: TestVariableResolver.java
@Test
public void testFunctionNamespace1() throws Exception {
    VariableResolver resolver = new VariableResolver();
    final List<Map<String, String>> l = new ArrayList<>();
    Map<String, String> m = new HashMap<>();
    m.put("name", "test");
    m.put("class", E.class.getName());
    l.add(m);
    resolver.setEvaluators(new DataImporter().getEvaluators(l));
    ContextImpl context = new ContextImpl(null, resolver, null, Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateMathParser dmp = new DateMathParser(TimeZone.getDefault());
    String s = resolver.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
    assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")), s);
    assertEquals("Hello World", resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}

55. TestVariableResolver#dateNamespaceWithExpr()

Project: lucene-solr
File: TestVariableResolver.java
@Test
public void dateNamespaceWithExpr() throws Exception {
    VariableResolver vri = new VariableResolver();
    vri.setEvaluators(new DataImporter().getEvaluators(Collections.<Map<String, String>>emptyList()));
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateMathParser dmp = new DateMathParser(TimeZone.getDefault());
    String s = vri.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
    assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")), s);
}

56. DateFormatTransformer#process()

Project: lucene-solr
File: DateFormatTransformer.java
private Date process(Object value, String format, Locale locale) throws ParseException {
    if (value == null)
        return null;
    String strVal = value.toString().trim();
    if (strVal.length() == 0)
        return null;
    SimpleDateFormat fmt = fmtCache.get(format);
    if (fmt == null) {
        fmt = new SimpleDateFormat(format, locale);
        fmtCache.put(format, fmt);
    }
    return fmt.parse(strVal);
}

57. RangeTest#testDate()

Project: Resteasy
File: RangeTest.java
@Test
public void testDate() {
    SimpleDateFormat dateFormatRFC822 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormatRFC822.setTimeZone(TimeZone.getTimeZone("GMT"));
    String format = dateFormatRFC822.format(new Date());
    System.out.println(format);
    try {
        Date date = dateFormatRFC822.parse(format);
        System.out.println(date.toString());
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

58. RedmineDateParser#parseLongFormat()

Project: redmine-java-api
File: RedmineDateParser.java
private static Date parseLongFormat(String dateStr) throws ParseException {
    final SimpleDateFormat format;
    if (dateStr.length() >= 5 && dateStr.charAt(4) == '/') {
        format = RedmineDateParser.FULL_DATE_FORMAT.get();
        return format.parse(dateStr);
    }
    dateStr = normalizeTimeZoneInfo(dateStr);
    if (dateStr.indexOf('.') < 0) {
        format = RedmineDateParser.FULL_DATE_FORMAT_V2.get();
    } else {
        format = RedmineDateParser.FULL_DATE_FORMAT_V3.get();
    }
    return format.parse(dateStr);
}

59. LSParseDateTime#_call()

Project: railo
File: LSParseDateTime.java
private static railo.runtime.type.dt.DateTime _call(PageContext pc, Object oDate, Locale locale, TimeZone tz, String format) throws PageException {
    if (oDate instanceof Date)
        return Caster.toDate(oDate, tz);
    String strDate = Caster.toString(oDate);
    // regular parse date time
    if (StringUtil.isEmpty(format, true))
        return DateCaster.toDateTime(locale, strDate, tz, locale.equals(Locale.US));
    // with java based format
    tz = ThreadLocalPageContext.getTimeZone(tz);
    if (locale == null)
        locale = pc.getLocale();
    SimpleDateFormat df = new SimpleDateFormat(format, locale);
    df.setTimeZone(tz);
    try {
        return new DateTimeImpl(df.parse(strDate));
    } catch (ParseException e) {
        throw Caster.toPageException(e);
    }
}

60. DateDeserializer#deserialize()

Project: quill
File: DateDeserializer.java
@Override
public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
    String date = element.getAsString();
    @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
        return formatter.parse(date);
    } catch (ParseException e) {
        Log.e(TAG, "Parsing failed: " + Log.getStackTraceString(e));
        return new Date();
    }
}

61. DateUtils#toDate()

Project: PlutusAndroid
File: DateUtils.java
/**
     * Formats a date using the locale date format
     *
     * @param date The date that will be formatted
     * @return if the locale is US a date of the format 'EEEE MMMM d, yyyy' will be returned, otherwise a date of the format 'EEEE d MMMM yyyy' will be returned
     */
public static String toDate(Date date) {
    SimpleDateFormat format;
    Locale locale = Locale.getDefault();
    if (locale.equals(Locale.US))
        format = new SimpleDateFormat("EEEE MMMM d, yyyy", Locale.US);
    else
        format = new SimpleDateFormat("EEEE d MMMM yyyy", Locale.getDefault());
    return format.format(date);
}

62. DateParser#parse()

Project: PinDroid
File: DateParser.java
public static Date parse(String input) throws java.text.ParseException {
    //NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
    //things a bit.  Before we go on we have to repair this.
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
    //this is zero time so we need to add that TZ indicator for 
    if (input.endsWith("Z")) {
        input = input.substring(0, input.length() - 1) + "GMT-00:00";
    } else {
        int inset = 6;
        String s0 = input.substring(0, input.length() - inset);
        String s1 = input.substring(input.length() - inset, input.length());
        input = s0 + "GMT" + s1;
    }
    return df.parse(input);
}

63. BuildVersion#getBuildDateAsLocalDate()

Project: pentaho-kettle
File: BuildVersion.java
public Date getBuildDateAsLocalDate() {
    SimpleDateFormat sdf = new SimpleDateFormat(JAR_BUILD_DATE_FORMAT);
    try {
        Date d = sdf.parse(buildDate);
        return d;
    // ignore failure, retry using standard format
    } catch (ParseException e) {
    }
    sdf = new SimpleDateFormat(ValueMeta.DEFAULT_DATE_FORMAT_MASK);
    try {
        Date d = sdf.parse(buildDate);
        return d;
    // ignore failure and return null
    } catch (ParseException e) {
    }
    return null;
}

64. ExsltDatetime#date()

Project: openjdk
File: ExsltDatetime.java
/**
     * The date:date function returns the date specified in the date/time string given
     * as the argument. If no argument is given, then the current local date/time, as
     * returned by date:date-time is used as a default argument.
     * The date/time string that's returned must be a string in the format defined as the
     * lexical representation of xs:dateTime in
     * <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">[3.2.7 dateTime]</a> of
     * <a href="http://www.w3.org/TR/xmlschema-2/">[XML Schema Part 2: Datatypes]</a>.
     * If the argument is not in either of these formats, date:date returns an empty string ('').
     * The date/time format is basically CCYY-MM-DDThh:mm:ss, although implementers should consult
     * <a href="http://www.w3.org/TR/xmlschema-2/">[XML Schema Part 2: Datatypes]</a> and
     * <a href="http://www.iso.ch/markete/8601.pdf">[ISO 8601]</a> for details.
     * The date is returned as a string with a lexical representation as defined for xs:date in
     * [3.2.9 date] of [XML Schema Part 2: Datatypes]. The date format is basically CCYY-MM-DD,
     * although implementers should consult [XML Schema Part 2: Datatypes] and [ISO 8601] for details.
     * If no argument is given or the argument date/time specifies a time zone, then the date string
     * format must include a time zone, either a Z to indicate Coordinated Universal Time or a + or -
     * followed by the difference between the difference from UTC represented as hh:mm. If an argument
     * is specified and it does not specify a time zone, then the date string format must not include
     * a time zone.
     */
public static String date(String datetimeIn) throws ParseException {
    String[] edz = getEraDatetimeZone(datetimeIn);
    String leader = edz[0];
    String datetime = edz[1];
    String zone = edz[2];
    if (datetime == null || zone == null)
        return EMPTY_STR;
    String[] formatsIn = { dt, d };
    String formatOut = d;
    Date date = testFormats(datetime, formatsIn);
    if (date == null)
        return EMPTY_STR;
    SimpleDateFormat dateFormat = new SimpleDateFormat(formatOut);
    dateFormat.setLenient(false);
    String dateOut = dateFormat.format(date);
    if (dateOut.length() == 0)
        return EMPTY_STR;
    else
        return (leader + dateOut + zone);
}

65. BuildIIWithEngine#buildII()

Project: kylin
File: BuildIIWithEngine.java
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;
}

66. BuildCubeWithEngine#testLeftJoinCubeWithSlr()

Project: kylin
File: BuildCubeWithEngine.java
@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;
}

67. BuildCubeWithEngine#testInnerJoinCubeWithView()

Project: kylin
File: BuildCubeWithEngine.java
@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;
}

68. BuildCubeWithEngine#testLeftJoinCubeWithView()

Project: kylin
File: BuildCubeWithEngine.java
@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;
}

69. BuildCubeWithEngine#testInnerJoinCubeWithoutSlr()

Project: kylin
File: BuildCubeWithEngine.java
@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;
}

70. BuildCubeWithEngine#testInnerJoinCubeWithSlr()

Project: kylin
File: BuildCubeWithEngine.java
@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;
}

71. CubingJob#initCubingJob()

Project: kylin
File: CubingJob.java
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;
}

72. CubeSegment#makeSegmentName()

Project: kylin
File: CubeSegment.java
/**
     * @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);
}

73. TestPartitionerProjection#testDateFormatPartitionerProjectStrict()

Project: kite
File: TestPartitionerProjection.java
@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);
}

74. ISODate#parseDateTime()

Project: jPOS
File: ISODate.java
/**
     * 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;
}

75. ISODate#parse()

Project: jPOS
File: ISODate.java
/**
     * 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;
}

76. Commentator#compareTo()

Project: JianDanRxJava
File: Commentator.java
@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;
    }
}

77. Comment4FreshNews#compareTo()

Project: JianDanRxJava
File: Comment4FreshNews.java
@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;
    }
}

78. Commentator#compareTo()

Project: JianDan
File: Commentator.java
@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;
    }
}

79. Comment4FreshNews#compareTo()

Project: JianDan
File: Comment4FreshNews.java
@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;
    }
}

80. NativeBytesTest#testDateTimes()

Project: Java-Lang
File: NativeBytesTest.java
@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()

Project: Java-Lang
File: DirectByteBufferBytesTest.java
@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. ByteBufferBytesTest#testDateTimes()

Project: Java-Lang
File: ByteBufferBytesTest.java
@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. SimpleDateFormatTest#test2038()

Project: j2objc
File: SimpleDateFormatTest.java
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)));
}

84. ASN1GeneralizedTime#setEncodingContent()

Project: j2objc
File: ASN1GeneralizedTime.java
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;
}

85. IrcMessage#getServerTimestampAsPrettyDate()

Project: IrssiNotifier
File: IrcMessage.java
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);
}

86. LoanDisbursementDetailsIntegrationTest#formatExpectedDisbursementDate()

Project: incubator-fineract
File: LoanDisbursementDetailsIntegrationTest.java
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;
}

87. HttpUtils#setDateAndCacheHeaders()

Project: hydra
File: HttpUtils.java
/**
     * 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())));
}

88. DatePickerDialog#getDisplayName()

Project: HoloEverywhere
File: DatePickerDialog.java
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());
}

89. FileContext#init()

Project: hadoop-20
File: FileContext.java
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);
}

90. DateTimeType#getPartString()

Project: h-store
File: DateTimeType.java
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);
}

91. AbstractCalendarListingWebScript#updateRepeatingStartEnd()

Project: community-edition
File: AbstractCalendarListingWebScript.java
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));
}

92. DateValidator#isValid()

Project: commons-validator
File: DateValidator.java
/**
     * <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;
}

93. FastDateParserTest#validateSdfFormatFdpParseEquality()

Project: commons-lang
File: FastDateParserTest.java
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;
        }
    }
}

94. FormattingDateConvertor#getDateFormat()

Project: cocoon
File: FormattingDateConvertor.java
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;
}

95. AuthUtil#checkExpiration()

Project: cmb
File: AuthUtil.java
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");
}

96. AuthUtil#checkTimeStampWithFormat()

Project: cmb
File: AuthUtil.java
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");
}

97. TracingControllerAndroid#startTracing()

Project: chromium_webview
File: TracingControllerAndroid.java
/**
     * 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);
}

98. RepoFileHandler#propfindFile()

Project: ceylon-compiler
File: RepoFileHandler.java
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");
}

99. RepoFileHandler#propfindFile()

Project: ceylon
File: RepoFileHandler.java
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");
}

100. JacksonMapper#init()

Project: cattle
File: JacksonMapper.java
@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());
    }
}