下面列出了怎么用java.text.DateFormat的API类实例代码及写法,或者点击链接到github查看源代码。
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";
}
}
}
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;
}
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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
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());
}
}
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));
}
}
@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();
}
}
/**
* 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);
}
}
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);
}
/**
* 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;
}
/**
* 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;
}
@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);
}
/**
* 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);
}
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);
}
}
@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;
}
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);
}
/**
* 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();
}
/**
* 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;
}
@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);
}
/**
* 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);
}
}
@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);
}
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());
}
/**
* 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);
}
/**
* 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 = "-";
}
/**
* 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)));
}
/**
* 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();
}
}
@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%'> </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();
}
/**
* 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));
}