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. 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);
}

3. 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();
}

4. 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;
}

5. 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());
}

6. 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());
}

7. 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);
}

8. 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 {@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);
}

9. 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()));
}

10. RestUtilsTest#getTimeFromDateStringTest()

Project: ambry
Source File: RestUtilsTest.java
View license
/**
   * 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"));
}

11. 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());
}

12. 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());
}

13. 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);
}

14. 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);
}

15. 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);
}

16. 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());
}

17. 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));
}

18. DateTimeUtils#parseDateFormat()

Project: calcite
Source File: DateTimeUtils.java
View license
//~ 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;
}

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 {@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);
}

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. DateUtil#formatDate()

View license
/**
     * 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);
}

25. 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);
}

26. 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;
}

27. 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();
}

28. CoinsetterFinancialTransactionTest#test()

View license
@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());
}

29. SublimeDatePicker#onLocaleChanged()

View license
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);
}

30. WeekOfYear#initDateFormat()

Project: StreamCQL
Source File: WeekOfYear.java
View license
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);
}

31. HttpHeadersTests#getDateFromHeader()

View license
// 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;
}

32. SlingDateValuesTest#testDateValues()

Project: sling
Source File: SlingDateValuesTest.java
View license
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);
    }
}

33. LogFileDeleter#deleteOldLogs()

Project: secor
Source File: LogFileDeleter.java
View license
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);
        }
    }
}

34. JsfUtil#convertISO8601StringToCalendar()

Project: sakai
Source File: JsfUtil.java
View license
/**
	 * 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;
}

35. JsfUtil#convertStringToTime()

Project: sakai
Source File: JsfUtil.java
View license
/**
	 * 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);
}

36. Iso8601DateFormat#format()

Project: sakai
Source File: Iso8601DateFormat.java
View license
/**
   * 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);
}

37. podHomeBean#convertDateString()

Project: sakai
Source File: podHomeBean.java
View license
/**
	 * 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;
}

38. BlogAtomFeedsTests#containsBlogPostFields()

Project: sagan
Source File: BlogAtomFeedsTests.java
View license
@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"));
}

39. EndomondoSynchronizer#parseFeed()

Project: runnerup
Source File: EndomondoSynchronizer.java
View license
/*
     * {"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();
        }
    }
}

40. NightscoutUploader#populateV1APICalibrationEntry()

Project: xDrip
Source File: NightscoutUploader.java
View license
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);
    }
}

41. NightscoutUploader#populateV1APIBGEntry()

Project: xDrip
Source File: NightscoutUploader.java
View license
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()));
}

42. OpenOrdersJSONTest#testUnmarshal()

Project: XChange
Source File: OpenOrdersJSONTest.java
View license
@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");
}

43. CoinsetterPriceAlertListTest#test()

View license
@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());
}

44. CoinsetterNewsAlertListTest#test()

View license
@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());
}

45. BTCETickerJSONTest#testUnmarshal()

Project: XChange
Source File: BTCETickerJSONTest.java
View license
@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
Source File: BittrexUtils.java
View license
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
Source File: BitstampAdapterTest.java
View license
@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
Source File: BitstampAdapterTest.java
View license
@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
Source File: RequestResource.java
View license
@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
Source File: JacksonModule.java
View license
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
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);
}

52. DateUtils#getDateFormat()

Project: uhabits
Source File: DateUtils.java
View license
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
Source File: XMLReporter.java
View license
/**
   * 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()

View license
@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()

View license
@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()

View license
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
Source File: RangeTest.java
View license
@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()

View license
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
Source File: LSParseDateTime.java
View license
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
Source File: DateDeserializer.java
View license
@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
Source File: DateUtils.java
View license
/**
     * 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
Source File: DateParser.java
View license
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
Source File: BuildVersion.java
View license
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
Source File: ExsltDatetime.java
View license
/**
     * 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
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;
}

66. 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;
}

67. 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;
}

68. 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;
}

69. 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;
}

70. 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;
}

71. 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;
}

72. 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);
}

73. 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);
}

74. 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;
}

75. 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;
}

76. 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;
    }
}

77. 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;
    }
}

78. 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;
    }
}

79. 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;
    }
}

80. 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));
}

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. 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));
}

83. 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)));
}

84. 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;
}

85. 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);
}

86. 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;
}

87. 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())));
}

88. 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());
}

89. 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;
}

90. OozieCLI#maskDate()

Project: oozie
Source File: OozieCLI.java
View license
private String maskDate(Date date, boolean isLocalTimeZone) {
    if (date == null) {
        return "-";
    }
    // SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd
    // HH:mm Z", Locale.US);
    SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
    if (!isLocalTimeZone) {
        dateFormater.setTimeZone(TimeZone.getTimeZone("GMT"));
    }
    return dateFormater.format(date);
}

91. 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.");
    }
}

92. AdminBlobStorageServiceTest#getNotModifiedBlobAndVerify()

View license
/**
   * Gets the blob with blob ID {@code 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);
}

93. AdminSecurityServiceTest#testGetNotModifiedBlob()

Project: ambry
Source File: AdminSecurityServiceTest.java
View license
/**
   * Tests {@link SecurityService#processResponse(RestRequest, RestResponseChannel, BlobInfo, Callback)} for a Get blob
   * with the passed in {@link BlobInfo} for a not modified response
   * @param blobInfo the {@link BlobInfo} to be used for the {@link RestRequest}
   * @param ifModifiedSinceMs the value (as a date string) of the {@link 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);
    }
}

94. AmbryBlobStorageServiceTest#getNotModifiedBlobAndVerify()

View license
/**
   * Gets the blob with blob ID {@code 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);
}

95. AmbrySecurityServiceTest#testGetNotModifiedBlob()

Project: ambry
Source File: AmbrySecurityServiceTest.java
View license
/**
   * Tests {@link SecurityService#processResponse(RestRequest, RestResponseChannel, BlobInfo, Callback)} for a Get blob
   * with the passed in {@link BlobInfo} for a not modified response
   * @param blobInfo the {@link BlobInfo} to be used for the {@link RestRequest}
   * @param ifModifiedSinceMs the value (as a date string) of the {@link 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);
    }
}

96. 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;
}

97. 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);
}

98. 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);
}

99. 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())));
}

100. 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);
}