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 Project: lams   Author: lamsfoundation   File: DateFormatConverter.java    License: 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 #2
Source Project: lucene-solr   Author: apache   File: TrecContentSource.java    License: 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 #3
Source Project: rapidoid   Author: rapidoid   File: Dates.java    License: 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 #4
Source Project: SIMVA-SoS   Author: SESoS   File: PeriodAxisLabelInfo.java    License: 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 #5
Source Project: rome   Author: rometools   File: DateParser.java    License: 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 #6
Source Project: desugar_jdk_libs   Author: google   File: DateTimeFormatterBuilder.java    License: 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 #7
Source Project: astor   Author: SpoonLabs   File: ExtendedMessageFormatTest.java    License: 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 #8
Source Project: arcusandroid   Author: arcus-smart-home   File: StringUtils.java    License: 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 #9
Source Project: olat   Author: huihoo   File: SystemPropertiesServiceITCase.java    License: 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 #10
Source Project: RipplePower   Author: cping   File: SkeinParameterSpec.java    License: 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 protected] 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 #11
Source Project: nebula   Author: eclipse   File: DateFormatter.java    License: 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 #12
Source Project: nebula   Author: eclipse   File: DateTimeFormatter.java    License: 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 #13
Source Project: arcusplatform   Author: arcus-smart-home   File: TestVideoRecordingFileName.java    License: 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 #14
Source Project: core   Author: Transitime   File: SiriMonitoredCall.java    License: 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 #15
Source Project: react-native-google-fit   Author: StasDoskalenko   File: SleepHistory.java    License: MIT License 5 votes vote down vote up
private void processDataSet(DataSet dataSet, Session session, WritableArray map) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    dateFormat.setTimeZone(TimeZone.getDefault());

    for (DataPoint dp : dataSet.getDataPoints()) {
        WritableMap sleepMap = Arguments.createMap();
        sleepMap.putString("value", dp.getValue(Field.FIELD_ACTIVITY).asActivity());
        sleepMap.putString("startDate", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        sleepMap.putString("endDate", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
        map.pushMap(sleepMap);
    }
}
 
Example #16
Source Project: azeroth   Author: warlock-china   File: DateTimeConvertDeserializer.java    License: 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 #17
Source Project: j2objc   Author: google   File: Support_MessageFormat.java    License: Apache License 2.0 5 votes vote down vote up
public void t_format_with_FieldPosition() {
	// This test assumes a default DateFormat.is24Hour setting.
               /* J2ObjC: DateFormat.is24Hour is Android-specific.
	DateFormat.is24Hour = null;*/

	String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} hamburger{2,choice,1#|1<s} and drank {1, number} liters of coke. That was {0,choice,1#just enough|1<more than enough} food!";
	MessageFormat format = new MessageFormat(pattern, Locale.US);

	Date date = new GregorianCalendar(2005, 1, 28, 14, 20, 16).getTime();
	Integer hamburgers = new Integer(8);
	Object[] objects = new Object[] { hamburgers, new Double(3.5),
			hamburgers, date, date };

	super.text = "On Feb 28, 2005 at 2:20:16 PM, he ate 8 hamburgers and drank 3.5 liters of coke. That was more than enough food!";

	// test with MessageFormat.Field.ARGUMENT
	t_FormatWithField(1, format, objects, null, Field.ARGUMENT, 3, 15);

	// test other format fields that are included in the formatted text
	t_FormatWithField(2, format, objects, null, DateFormat.Field.AM_PM, 0,
			0);
	t_FormatWithField(3, format, objects, null,
			NumberFormat.Field.FRACTION, 0, 0);

	// test fields that are not included in the formatted text
	t_FormatWithField(4, format, objects, null, DateFormat.Field.ERA, 0, 0);
	t_FormatWithField(5, format, objects, null,
			NumberFormat.Field.EXPONENT_SIGN, 0, 0);
}
 
Example #18
Source Project: javamelody   Author: javamelody   File: MHtmlWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Exporte une JTable dans un fichier au format html.
 *
 * @param table
 *           MBasicTable
 * @param outputStream
 *           OutputStream
 * @param isSelection
 *           boolean
 * @throws IOException
 *            Erreur disque
 */
protected void writeHtml(final MBasicTable table, final OutputStream outputStream,
		final boolean isSelection) throws IOException {
	final Writer out = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);

	final String eol = isSelection ? "\n" : System.getProperty("line.separator");
	// eol = "\n" si sélection, "\r\n" sinon pour un fichier windows et "\n" pour un fichier unix

	out.write("<!-- Fichier genere par ");
	out.write(System.getProperty("user.name"));
	out.write(" le ");
	out.write(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG)
			.format(new Date()));
	out.write(" -->");
	out.write(eol);

	out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.write("<html>");
	out.write(eol);
	final String title = buildTitle(table);
	writeHtmlHead(title, out, eol);
	out.write("<body>");
	out.write(eol);
	if (title != null) {
		out.write("<h3>");
		out.write(title);
		out.write("</h3>");
	}
	out.write(eol);

	writeHtmlTable(table, isSelection, out, eol);
	out.write("</body>");
	out.write(eol);
	out.write("</html>");
	out.flush();
}
 
Example #19
Source Project: astor   Author: SpoonLabs   File: DateAxis.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Estimates the maximum width of the tick labels, assuming the specified
 * tick unit is used.
 * <P>
 * Rather than computing the string bounds of every tick on the axis, we
 * just look at two values: the lower bound and the upper bound for the
 * axis.  These two values will usually be representative.
 *
 * @param g2  the graphics device.
 * @param unit  the tick unit to use for calculation.
 *
 * @return The estimated maximum width of the tick labels.
 */
private double estimateMaximumTickLabelHeight(Graphics2D g2,
                                              DateTickUnit unit) {

    RectangleInsets tickLabelInsets = getTickLabelInsets();
    double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();

    Font tickLabelFont = getTickLabelFont();
    FontRenderContext frc = g2.getFontRenderContext();
    LineMetrics lm = tickLabelFont.getLineMetrics("ABCxyz", frc);
    if (!isVerticalTickLabels()) {
        // all tick labels have the same width (equal to the height of
        // the font)...
        result += lm.getHeight();
    }
    else {
        // look at lower and upper bounds...
        DateRange range = (DateRange) getRange();
        Date lower = range.getLowerDate();
        Date upper = range.getUpperDate();
        String lowerStr = null;
        String upperStr = null;
        DateFormat formatter = getDateFormatOverride();
        if (formatter != null) {
            lowerStr = formatter.format(lower);
            upperStr = formatter.format(upper);
        }
        else {
            lowerStr = unit.dateToString(lower);
            upperStr = unit.dateToString(upper);
        }
        FontMetrics fm = g2.getFontMetrics(tickLabelFont);
        double w1 = fm.stringWidth(lowerStr);
        double w2 = fm.stringWidth(upperStr);
        result += Math.max(w1, w2);
    }

    return result;

}
 
Example #20
Source Project: agile-service-old   Author: choerodon   File: SprintServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SprintDetailVO startSprint(Long projectId, SprintUpdateVO sprintUpdateVO) {
    if (!Objects.equals(projectId, sprintUpdateVO.getProjectId())) {
        throw new CommonException(NOT_EQUAL_ERROR);
    }
    if (sprintMapper.selectCountByStartedSprint(projectId) != 0) {
        throw new CommonException(START_SPRINT_ERROR);
    }
    SprintConvertDTO sprintConvertDTO = sprintUpdateAssembler.toTarget(sprintUpdateVO, SprintConvertDTO.class);
    sprintConvertDTO.checkDate();
    sprintValidator.checkSprintStartInProgram(sprintConvertDTO);
    sprintConvertDTO.startSprint();
    if (sprintUpdateVO.getWorkDates() != null && !sprintUpdateVO.getWorkDates().isEmpty()) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        sprintUpdateVO.getWorkDates().forEach(workDates -> {
            WorkCalendarRefDTO workCalendarRefDTO = new WorkCalendarRefDTO();
            workCalendarRefDTO.setSprintId(sprintConvertDTO.getSprintId());
            workCalendarRefDTO.setProjectId(sprintConvertDTO.getProjectId());
            workCalendarRefDTO.setWorkDay(workDates.getWorkDay());
            try {
                calendar.setTime(dateFormat.parse(workDates.getWorkDay()));
            } catch (ParseException e) {
                throw new CommonException("ParseException{}", e);
            }
            workCalendarRefDTO.setYear(calendar.get(Calendar.YEAR));
            workCalendarRefDTO.setStatus(workDates.getStatus());
            workCalendarRefService.create(workCalendarRefDTO);
        });
    }
    issueAccessDataService.updateStayDate(projectId, sprintConvertDTO.getSprintId(), new Date());
    return sprintUpdateAssembler.toTarget(update(sprintConvertDTO), SprintDetailVO.class);
}
 
Example #21
Source Project: framework   Author: ww20081120   File: DateUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author yang.zhipeng <br>
 * @taskId <br>
 * @param date <br>
 * @param format <br>
 * @return <br>
 */
public static Date string2Date(final String date, final String format) {
    if (StringUtils.isEmpty(format)) {
        throw new IllegalArgumentException("the date format string is null!");
    }
    DateFormat sdf = new SimpleDateFormat(format);
    try {
        return sdf.parse(date.trim());
    }
    catch (ParseException e) {
        throw new IllegalArgumentException("the date string " + date + " is not matching format: " + format, e);
    }
}
 
Example #22
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TCKLocalizedPrinterParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test(dataProvider="time")
public void test_time_parse(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) {
    DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale);
    Date oldDate = new Date(1970, 0, 0, time.getHour(), time.getMinute(), time.getSecond());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale);
    TemporalAccessor parsed = f.parse(text, pos);
    assertEquals(pos.getIndex(), text.length());
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(LocalTime.from(parsed), time);
}
 
Example #23
Source Project: pay   Author: 1991wangliang   File: AlipayLogger.java    License: Apache License 2.0 5 votes vote down vote up
public static void logBizError(String rsp) {
    if (!needEnableLogger) {
        return;
    }
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
    StringBuilder sb = new StringBuilder();
    sb.append(df.format(new Date()));
    sb.append("^_^");
    sb.append(rsp);
    blog.error(sb.toString());
}
 
Example #24
Source Project: baratine   Author: baratine   File: QDate.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a date in H:mm:ss PM format.
 */
public String printShortLocaleTime()
{
  _date.setTime(_localTimeOfEpoch);

  if (_shortTimeFormat == null)
    _shortTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);

  return _shortTimeFormat.format(_date);
}
 
Example #25
Source Project: opensim-gui   Author: opensim-org   File: AbstractCategoryItemLabelGenerator.java    License: 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 #26
Source Project: pacbot   Author: tmobile   File: CommonUtils.java    License: 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 #27
Source Project: sakai   Author: sakaiproject   File: UserLocale.java    License: 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 #28
Source Project: lemon   Author: xuhuisheng   File: BpmPortalController.java    License: 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 #29
Source Project: lutece-core   Author: lutece-platform   File: I18nServiceTest.java    License: 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));    
   }
 
Example #30
Source Project: nifi   Author: apache   File: AbstractJsonRowRecordReader.java    License: 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);
    }
}