java.text.DateFormat Java Examples

The following examples show how to use java.text.DateFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SiriMonitoredCall.java    From core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructs a MonitoredCall element.
 * 
 * @param ipcCompleteVehicle
 * @param prediction
 *            The prediction for when doing stop monitoring. When doing
 *            vehicle monitoring should be set to null.
 * @param timeFormatter
 *            For converting epoch time into a Siri time string
 */
public SiriMonitoredCall(IpcVehicleComplete ipcCompleteVehicle,
		IpcPrediction prediction, DateFormat timeFormatter) {
	stopPointRef = ipcCompleteVehicle.getNextStopId();
	// Always using value of 1 for now
	visitNumber = 1;

	// Deal with the predictions if StopMonitoring query.
	// Don't have schedule time available so can't provide it.
	if (prediction != null) {
		if (prediction.isArrival()) {
			expectedArrivalTime =
					timeFormatter.format(new Date(prediction.getPredictionTime()));
		} else {
			expectedDepartureTime =
					timeFormatter.format(new Date(prediction.getPredictionTime()));
		}
	}

	// Deal with NYC MTA extensions
	extensions = new Extensions(ipcCompleteVehicle);
}
 
Example #2
Source File: DateFormatConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static String getJavaDateTimePattern(int style, Locale locale) {
   	DateFormat df = DateFormat.getDateTimeInstance(style, style, locale);
   	if( df instanceof SimpleDateFormat ) {
   		return ((SimpleDateFormat)df).toPattern();
   	} else {
   		switch( style ) {
   		case DateFormat.SHORT:
   			return "M/d/yy h:mm a";
   		case DateFormat.MEDIUM:
   			return "MMM d, yyyy h:mm:ss a";
   		case DateFormat.LONG:
   			return "MMMM d, yyyy h:mm:ss a";
   		case DateFormat.FULL:
   			return "dddd, MMMM d, yyyy h:mm:ss a";
   		default:
   			return "MMM d, yyyy h:mm:ss a";
   		}
   	}
}
 
Example #3
Source File: StringUtils.java    From arcusandroid with Apache License 2.0 6 votes vote down vote up
public static SpannableString getDashboardDateString (Date dateValue) {
    DateFormat timeFormat = new SimpleDateFormat("h:mm", Locale.US);
    DateFormat ampmFormat = new SimpleDateFormat(" a", Locale.US);
    DateFormat dateFormat = new SimpleDateFormat("MMM d", Locale.US);

    if (dateValue == null) {
        return new SpannableString("");
    }

    // Date is today; just show the time
    else if (StringUtils.isDateToday(dateValue)) {

        return StringUtils.getSuperscriptSpan(timeFormat.format(dateValue), ampmFormat.format(dateValue));
    }

    // Date is yesterday; show "YESTERDAY"
    else if (StringUtils.isDateYesterday(dateValue)) {
        return new SpannableString(ArcusApplication.getContext().getString(R.string.yesterday));
    }

    // Date is in the past; show date
    else {
        return new SpannableString(dateFormat.format(dateValue));
    }
}
 
Example #4
Source File: TrecContentSource.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public Date parseDate(String dateStr) {
  dateStr = dateStr.trim();
  DateFormatInfo dfi = getDateFormatInfo();
  for (int i = 0; i < dfi.dfs.length; i++) {
    DateFormat df = dfi.dfs[i];
    dfi.pos.setIndex(0);
    dfi.pos.setErrorIndex(-1);
    Date d = df.parse(dateStr, dfi.pos);
    if (d != null) {
      // Parse succeeded.
      return d;
    }
  }
  // do not fail test just because a date could not be parsed
  if (verbose) {
    System.out.println("failed to parse date (assigning 'now') for: " + dateStr);
  }
  return null; 
}
 
Example #5
Source File: Dates.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
public static byte[] getDateTimeBytes() {
	long time = System.currentTimeMillis();

	// avoid synchronization for better performance
	if (time >= updateCurrDateAfter) {

		// RFC 1123 date-time format, e.g. Sun, 07 Sep 2014 00:17:29 GMT
		DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ROOT);
		dateFormat.setTimeZone(GMT);

		Date date = new Date();
		date.setTime(time);

		CURR_DATE_BYTES = dateFormat.format(date).getBytes();
		updateCurrDateAfter = time - (time % 1000) + 1000;
	}

	return CURR_DATE_BYTES;
}
 
Example #6
Source File: PeriodAxisLabelInfo.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param periodClass  the subclass of {@link RegularTimePeriod} to use
 *                     (<code>null</code> not permitted).
 * @param dateFormat  the date format (<code>null</code> not permitted).
 * @param padding  controls the space around the band (<code>null</code>
 *                 not permitted).
 * @param labelFont  the label font (<code>null</code> not permitted).
 * @param labelPaint  the label paint (<code>null</code> not permitted).
 * @param drawDividers  a flag that controls whether dividers are drawn.
 * @param dividerStroke  the stroke used to draw the dividers
 *                       (<code>null</code> not permitted).
 * @param dividerPaint  the paint used to draw the dividers
 *                      (<code>null</code> not permitted).
 */
public PeriodAxisLabelInfo(Class periodClass, DateFormat dateFormat,
        RectangleInsets padding, Font labelFont, Paint labelPaint,
        boolean drawDividers, Stroke dividerStroke, Paint dividerPaint) {
    ParamChecks.nullNotPermitted(periodClass, "periodClass");
    ParamChecks.nullNotPermitted(dateFormat, "dateFormat");
    ParamChecks.nullNotPermitted(padding, "padding");
    ParamChecks.nullNotPermitted(labelFont, "labelFont");
    ParamChecks.nullNotPermitted(labelPaint, "labelPaint");
    ParamChecks.nullNotPermitted(dividerStroke, "dividerStroke");
    ParamChecks.nullNotPermitted(dividerPaint, "dividerPaint");
    this.periodClass = periodClass;
    this.dateFormat = (DateFormat) dateFormat.clone();
    this.padding = padding;
    this.labelFont = labelFont;
    this.labelPaint = labelPaint;
    this.drawDividers = drawDividers;
    this.dividerStroke = dividerStroke;
    this.dividerPaint = dividerPaint;
}
 
Example #7
Source File: DateParser.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a Date out of a string using an array of masks.
 * <p/>
 * It uses the masks in order until one of them succedes or all fail.
 * <p/>
 *
 * @param masks array of masks to use for parsing the string
 * @param sDate string to parse for a date.
 * @return the Date represented by the given string using one of the given masks. It returns
 *         <b>null</b> if it was not possible to parse the the string with any of the masks.
 *
 */
private static Date parseUsingMask(final String[] masks, String sDate, final Locale locale) {
    if (sDate != null) {
        sDate = sDate.trim();
    }
    ParsePosition pp = null;
    Date d = null;
    for (int i = 0; d == null && i < masks.length; i++) {
        final DateFormat df = new SimpleDateFormat(masks[i].trim(), locale);
        // df.setLenient(false);
        df.setLenient(true);
        try {
            pp = new ParsePosition(0);
            d = df.parse(sDate, pp);
            if (pp.getIndex() != sDate.length()) {
                d = null;
            }
        } catch (final Exception ex1) {
        }
    }
    return d;
}
 
Example #8
Source File: DateTimeFormatterBuilder.java    From desugar_jdk_libs with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the formatting pattern for date and time styles for a locale and chronology.
 * The locale and chronology are used to lookup the locale specific format
 * for the requested dateStyle and/or timeStyle.
 *
 * @param dateStyle  the FormatStyle for the date, null for time-only pattern
 * @param timeStyle  the FormatStyle for the time, null for date-only pattern
 * @param chrono  the Chronology, non-null
 * @param locale  the locale, non-null
 * @return the locale and Chronology specific formatting pattern
 * @throws IllegalArgumentException if both dateStyle and timeStyle are null
 */
public static String getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle,
        Chronology chrono, Locale locale) {
    Objects.requireNonNull(locale, "locale");
    Objects.requireNonNull(chrono, "chrono");
    if (dateStyle == null && timeStyle == null) {
        throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null");
    }
    // For desugar: avoid JDK internal localization helpers
    // LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale);
    // String pattern = lr.getJavaTimeDateTimePattern(
    //         convertStyle(timeStyle), convertStyle(dateStyle), chrono.getCalendarType());
    // return pattern;
    DateFormat format;
    if (timeStyle == null) {
        format = DateFormat.getDateInstance(dateStyle.ordinal(), locale);
    } else if (dateStyle == null) {
        format = DateFormat.getTimeInstance(timeStyle.ordinal(), locale);
    } else {
        format = DateFormat.getDateTimeInstance(dateStyle.ordinal(), timeStyle.ordinal(), locale);
    }
    if (format instanceof SimpleDateFormat) {
        return ((SimpleDateFormat) format).toPattern();
    }
    throw new UnsupportedOperationException("Can't determine pattern from " + format);
}
 
Example #9
Source File: ExtendedMessageFormatTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testOverriddenBuiltinFormat() {
    Calendar cal = Calendar.getInstance();
    cal.set(2007, Calendar.JANUARY, 23);
    Object[] args = new Object[] {cal.getTime()};
    Locale[] availableLocales = DateFormat.getAvailableLocales();
    Map<String, ? extends FormatFactory> registry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());

    //check the non-overridden builtins:
    checkBuiltInFormat("1: {0,date}", registry,          args, availableLocales);
    checkBuiltInFormat("2: {0,date,medium}", registry,   args, availableLocales);
    checkBuiltInFormat("3: {0,date,long}", registry,     args, availableLocales);
    checkBuiltInFormat("4: {0,date,full}", registry,     args, availableLocales);
    checkBuiltInFormat("5: {0,date,d MMM yy}", registry, args, availableLocales);

    //check the overridden format:
    for (int i = -1; i < availableLocales.length; i++) {
        Locale locale = i < 0 ? null : availableLocales[i];
        MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
        String pattern = "{0,date,short}";
        ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, registry);
        assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args));
        assertEquals("overridden date,short pattern", pattern, dateShort.toPattern());
    }
}
 
Example #10
Source File: SystemPropertiesServiceITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetProperty() {
    try {
        Thread.sleep(1000); // wait until jms is ready
        String value = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(new Date());
        propertiesService.setProperty(PropertyLocator.DB_VENDOR, value);
        String result = propertiesService.getStringProperty(PropertyLocator.DB_VENDOR);

        // reset property to default value
        propertiesService.setProperty(PropertyLocator.DB_VENDOR, "test");

        assertEquals(value, result);
        Thread.sleep(1000);

        // count the messages the listener should have received
        // this simulates the message broadcast in the cluster
        assertEquals(2, messageListener.messageCount);
    } catch (InterruptedException e) {
        e.printStackTrace();
        fail();
    }

}
 
Example #11
Source File: SkeinParameterSpec.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
/**
 * Implements the recommended personalisation format for Skein defined in Section 4.11 of
 * the Skein 1.3 specification. You may need to use this method if the default locale
 * doesn't use a Gregorian calender so that the GeneralizedTime produced is compatible implementations.
 * <p>
 * The format is <code>YYYYMMDD email@address distinguisher</code>, encoded to a byte
 * sequence using UTF-8 encoding.
 *
 * @param date          the date the personalised application of the Skein was defined.
 * @param dateLocale    locale to be used for date interpretation.
 * @param emailAddress  the email address of the creation of the personalised application.
 * @param distinguisher an arbitrary personalisation string distinguishing the application.
 * @return the current builder.
 */
public Builder setPersonalisation(Date date, Locale dateLocale, String emailAddress, String distinguisher)
{
    try
    {
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        final OutputStreamWriter out = new OutputStreamWriter(bout, "UTF-8");
        final DateFormat format = new SimpleDateFormat("YYYYMMDD", dateLocale);
        out.write(format.format(date));
        out.write(" ");
        out.write(emailAddress);
        out.write(" ");
        out.write(distinguisher);
        out.close();
        return set(PARAM_TYPE_PERSONALISATION, bout.toByteArray());
    }
    catch (IOException e)
    {
        throw new IllegalStateException("Byte I/O failed: " + e);
    }
}
 
Example #12
Source File: DateFormatter.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
  * Returns the default edit pattern for the given <code>Locale</code>.<p>
  * 
  * A <code>DateFormat</code> object is instantiated with SHORT format for
  * both the date part for the given locale. The corresponding pattern
  * string is then retrieved by calling the <code>toPattern</code>.<p>
  * 
  * Default patterns are stored in a cache with ISO3 language and country codes
  * as key. So they are computed only once by locale.
  * 
  * @param loc locale
  * @return edit pattern for the locale
  */
public String getDefaultEditPattern(Locale loc) {
	if ( loc == null ) {
		loc = Locale.getDefault();
	}
	String key = "DA" + loc.toString();
	String pattern = (String) cachedPatterns.get(key);
	if ( pattern == null ) {
		DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
		if ( ! (df instanceof SimpleDateFormat) ) {
			throw new IllegalArgumentException("No default pattern for locale " + loc.getDisplayName());
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append(((SimpleDateFormat) df).toPattern());
		int i;
		if ( buffer.indexOf("yyy") < 0 && (i = buffer.indexOf("yy")) >= 0 ) {
			buffer.insert(i, "yy");
		}
		pattern = buffer.toString();
		cachedPatterns.put(key, pattern);
	}
	return pattern;
}
 
Example #13
Source File: DateTimeFormatter.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
  * Returns the default edit pattern for the given <code>Locale</code>.<p>
  *
  * A <code>DateFormat</code> object is instantiated with SHORT format for
  * both date and time parts for the given locale. The corresponding pattern
  * string is then retrieved by calling the <code>toPattern</code>.<p>
  *
  * Default patterns are stored in a cache with ISO3 language and country codes
  * as key. So they are computed only once by locale.
  *
  * @param loc locale
  * @return edit pattern for the locale
  */
public String getDefaultEditPattern(Locale loc) {
	if ( loc == null ) {
		loc = Locale.getDefault();
	}
	String key = "DT" + loc.toString();
	String pattern = cachedPatterns.get(key);
	if ( pattern == null ) {
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, loc);
		if ( ! (df instanceof SimpleDateFormat) ) {
			throw new IllegalArgumentException("No default pattern for locale " + loc.getDisplayName());
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append(((SimpleDateFormat) df).toPattern());
		int i;
		if ( buffer.indexOf("yyy") < 0 && (i = buffer.indexOf("yy")) >= 0 ) {
			buffer.insert(i, "yy");
		}
		pattern = buffer.toString();
		cachedPatterns.put(key, pattern);
	}
	return pattern;
}
 
Example #14
Source File: TestVideoRecordingFileName.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void localDateSuffix() throws ParseException {
   Place place = Fixtures.createPlace();
   place.setTzId("US/Central");

   VideoRecordingFileName sut = new VideoRecordingFileName(
         UUID.randomUUID(),
         UUID.randomUUID(),
         place.getId(),
         createNiceMock(DeviceDAO.class),
         createNiceMock(PlaceDAO.class));

   DateFormat utcFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
   utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

   Date date = utcFormat.parse("06/01/2015 11:20:04.453");

   String result = sut.localDateSuffix(place, date);

   Assert.assertEquals("20150601_062004", result);
}
 
Example #15
Source File: DateTimeConvertDeserializer.java    From azeroth with Apache License 2.0 5 votes vote down vote up
@Override
public Date deserialize(JsonParser jsonParser,
                        DeserializationContext dc) throws JsonProcessingException {
    Date date = null;
    DateFormat dateFormat = new SimpleDateFormat(pattern);
    try {
        String val = jsonParser.getText();

        date = dateFormat.parse(val);
    } catch (ParseException | IOException pex) {
        throw new RuntimeException("json转换Date异常,格式:" + pattern);
    }

    return date;
}
 
Example #16
Source File: Bug8001562.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    List<Locale> avail = Arrays.asList(BreakIterator.getAvailableLocales());
    diffLocale(BreakIterator.class, avail);

    avail = Arrays.asList(Collator.getAvailableLocales());
    diffLocale(Collator.class, avail);

    avail = Arrays.asList(DateFormat.getAvailableLocales());
    diffLocale(DateFormat.class, avail);

    avail = Arrays.asList(DateFormatSymbols.getAvailableLocales());
    diffLocale(DateFormatSymbols.class, avail);

    avail = Arrays.asList(DecimalFormatSymbols.getAvailableLocales());
    diffLocale(DecimalFormatSymbols.class, avail);

    avail = Arrays.asList(NumberFormat.getAvailableLocales());
    diffLocale(NumberFormat.class, avail);

    avail = Arrays.asList(Locale.getAvailableLocales());
    diffLocale(Locale.class, avail);
}
 
Example #17
Source File: Numbers.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * @param buffer The string to convert.
 * @return The number of milliseconds since midnight, January 1, 1970.
 */
public static long extractDate(String buffer) {
    if (buffer != null) {
        buffer = buffer.trim();
        for (int i = DateFormat.FULL; i <= DateFormat.SHORT; i++) {
            try {
                return DateFormat.getDateInstance(i).parse(buffer).getTime();
            } catch (Exception exception) {
                // Ignore
            }
        }
    }
    return System.currentTimeMillis();
}
 
Example #18
Source File: Bug4807540.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    Locale si = new Locale("sl", "si");

    String expected = "30.4.2008";
    DateFormat dfSi = DateFormat.getDateInstance (DateFormat.MEDIUM, si);

    String siString = new String (dfSi.format(new Date(108, Calendar.APRIL, 30)));

    if (expected.compareTo(siString) != 0) {
        throw new RuntimeException("Error: " + siString  + " should be " + expected);
    }
}
 
Example #19
Source File: AbstractCategoryItemLabelGenerator.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a label generator with the specified date formatter.
 *
 * @param labelFormat  the label format string (<code>null</code> not 
 *                     permitted).
 * @param formatter  the date formatter (<code>null</code> not permitted).
 */
protected AbstractCategoryItemLabelGenerator(String labelFormat, 
                                             DateFormat formatter) {
    if (labelFormat == null) {
        throw new IllegalArgumentException("Null 'labelFormat' argument.");
    }
    if (formatter == null) {
        throw new IllegalArgumentException("Null 'formatter' argument.");
    }
    this.labelFormat = labelFormat;
    this.numberFormat = null;
    this.percentFormat = NumberFormat.getPercentInstance();
    this.dateFormat = formatter;
    this.nullValueString = "-";
}
 
Example #20
Source File: DateUtils.java    From tianti with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param source
 * @param pattern
 * @return
 */
public static Date parseDate(String source, String pattern){
	if(StringUtils.isBlank(source)){
		return null;
	}
	Date date = null;
	try {
		DateFormat dateFormat = new SimpleDateFormat(pattern);
		date = dateFormat.parse(source.trim());
	} catch (ParseException e) {
		LOG.error("解析时间异常:["+source+"] " + e.getMessage());
	}
	return date;
}
 
Example #21
Source File: AbstractJsonRowRecordReader.java    From nifi with Apache License 2.0 5 votes vote down vote up
public AbstractJsonRowRecordReader(final InputStream in, final ComponentLog logger, final String dateFormat, final String timeFormat, final String timestampFormat)
        throws IOException, MalformedRecordException {

    this.logger = logger;

    final DateFormat df = dateFormat == null ? null : DataTypeUtils.getDateFormat(dateFormat);
    final DateFormat tf = timeFormat == null ? null : DataTypeUtils.getDateFormat(timeFormat);
    final DateFormat tsf = timestampFormat == null ? null : DataTypeUtils.getDateFormat(timestampFormat);

    LAZY_DATE_FORMAT = () -> df;
    LAZY_TIME_FORMAT = () -> tf;
    LAZY_TIMESTAMP_FORMAT = () -> tsf;

    try {
        jsonParser = jsonFactory.createJsonParser(in);
        jsonParser.setCodec(codec);

        JsonToken token = jsonParser.nextToken();
        if (token == JsonToken.START_ARRAY) {
            token = jsonParser.nextToken(); // advance to START_OBJECT token
        }

        if (token == JsonToken.START_OBJECT) { // could be END_ARRAY also
            firstJsonNode = jsonParser.readValueAsTree();
        } else {
            firstJsonNode = null;
        }
    } catch (final JsonParseException e) {
        throw new MalformedRecordException("Could not parse data as JSON", e);
    }
}
 
Example #22
Source File: BpmPortalController.java    From lemon with Apache License 2.0 5 votes vote down vote up
@RequestMapping("processes")
public String processes() {
    String tenantId = tenantHolder.getTenantId();
    String hql = "from BpmProcess where tenantId=? order by priority";
    List<BpmProcess> bpmProcesses = bpmProcessManager.find(hql, tenantId);

    StringBuilder buff = new StringBuilder();
    buff.append("<table class='table table-hover'>");
    buff.append("  <thead>");
    buff.append("    <tr>");
    buff.append("      <th>名称</th>");
    buff.append("      <th width='15%'>&nbsp;</th>");
    buff.append("    </tr>");
    buff.append("  </thead>");
    buff.append("  <tbody>");

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (BpmProcess bpmProcess : bpmProcesses) {
        buff.append("    <tr>");
        // buff.append("      <td>" + bpmProcess.getName() + "(" + bpmProcess.getCode() + ")</td>");
        buff.append("      <td>" + bpmProcess.getName() + "</td>");
        buff.append("      <td>");
        buff.append("        <a href='"
                + ".."
                + "/operation/process-operation-viewStartForm.do?bpmProcessId="
                + bpmProcess.getId()
                + "' class='btn btn-xs btn-primary'>发起</a>");
        buff.append("      </td>");
        buff.append("    </tr>");
    }

    buff.append("  </tbody>");
    buff.append("</table>");

    return buff.toString();
}
 
Example #23
Source File: UserLocale.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Get the date format from the locale
 * @return
 */
public String getDateFormat() {

	Locale locale = new ResourceLoader().getLocale();
	DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
	try {
		return ((SimpleDateFormat)df).toPattern();
	} catch (ClassCastException cce) {
		log.warn("Failed to cast DateFormat into SimpleDateFormat for locale {}", locale.toString());
		return new SimpleDateFormat().toPattern();
	}
}
 
Example #24
Source File: DateUtils.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
public static Timestamp gettimestamp() {
    Date dt = new Date();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String nowTime = df.format(dt);
    java.sql.Timestamp buydate = java.sql.Timestamp.valueOf(nowTime);
    return buydate;
}
 
Example #25
Source File: TestUtils.java    From k8s-fleetman with MIT License 5 votes vote down vote up
public static Date getDateFrom(String timestamp)
{
	DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
	try {
		return format.parse(timestamp);
	} 
	catch (ParseException e) 
	{
		// code error
		throw new RuntimeException(e);
	} 
}
 
Example #26
Source File: IntervalCategoryItemLabelGeneratorTest.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
@Test
public void testSerialization() {
    IntervalCategoryItemLabelGenerator g1
            = new IntervalCategoryItemLabelGenerator("{3} - {4}",
            DateFormat.getInstance());
    IntervalCategoryItemLabelGenerator g2 = (IntervalCategoryItemLabelGenerator) TestUtilities.serialised(g1);
    assertEquals(g1, g2);
}
 
Example #27
Source File: Arja_0071_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale != null) {
        key = new Pair(key, locale);
    }

    FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);
        
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example #28
Source File: CommonUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Date format.
 *
 * @param dateInString the date in string
 * @param formatFrom the format from
 * @param formatTo the format to
 * @return the date
 * @throws ParseException the parse exception
 */
public static Date dateFormat(final String dateInString, String formatFrom, String formatTo)
        throws java.text.ParseException {
    String dateDormatter = "MM/dd/yyyy";
    if (StringUtils.isNullOrEmpty(formatFrom)) {
        formatFrom = dateDormatter;
    }
    if (StringUtils.isNullOrEmpty(formatTo)) {
        formatTo = dateDormatter;
    }
    DateFormat dateFromFormater = new SimpleDateFormat(formatFrom);
    DateFormat dateToFormater = new SimpleDateFormat(formatTo);
    return dateToFormater.parse(dateToFormater.format(dateFromFormater.parse(dateInString)));
}
 
Example #29
Source File: ConferenceApiTest.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testRegistrations() throws Exception {
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = dateFormat.parse("03/25/2014");
    Date endDate = dateFormat.parse("03/26/2014");
    List<String> topics = new ArrayList<>();
    topics.add("Google");
    topics.add("Cloud");
    topics.add("Platform");
    ConferenceForm conferenceForm = new ConferenceForm(
            NAME, DESCRIPTION, topics, CITY, startDate, endDate, CAP);
    Conference conference = conferenceApi.createConference(user, conferenceForm);
    // Registration
    Boolean result = conferenceApi.registerForConference(
            user, conference.getWebsafeKey()).getResult();
    conference = conferenceApi.getConference(conference.getWebsafeKey());
    Profile profile = ofy().load().key(Key.create(Profile.class, user.getUserId())).now();
    assertTrue("registerForConference should succeed.", result);
    assertEquals(CAP - 1, conference.getSeatsAvailable());
    assertTrue("Profile should have the conferenceId in conferenceIdsToAttend.",
            profile.getConferenceKeysToAttend().contains(conference.getWebsafeKey()));

    // Unregister
    result = conferenceApi.unregisterFromConference(
            user, conference.getWebsafeKey()).getResult();
    conference = conferenceApi.getConference(conference.getWebsafeKey());
    profile = ofy().load().key(Key.create(Profile.class, user.getUserId())).now();
    assertTrue("unregisterFromConference should succeed.", result);
    assertEquals(CAP, conference.getSeatsAvailable());
    assertFalse("Profile shouldn't have the conferenceId in conferenceIdsToAttend.",
            profile.getConferenceKeysToAttend().contains(conference.getWebsafeKey()));
}
 
Example #30
Source File: I18nServiceTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
    * Test of getLocalizedDate method, of class fr.paris.lutece.portal.service.i18n.I18nService.
    */
   public void testGetLocalizedDate( )
   {
       System.out.println( "getLocalizedDate" );

       Date date = new Date( 0 );
       Locale locale = Locale.FRENCH;
       int nDateFormat = DateFormat.SHORT;

       String expResultJava8 = "01/01/70";
String expResultJava10 = "01/01/1970";
String result = fr.paris.lutece.portal.service.i18n.I18nService.getLocalizedDate( date, locale, nDateFormat );
assertTrue(expResultJava8.equals(result) || expResultJava10.equals(result));    
   }