简体   繁体   中英

Date formatting using Joda time library

In a java class, i get the date as string say "renewDate" from the datepicker-input form in mm/dd/yyyy.

When i try to update in the code using joda time library

DateTime expireDate = new DateTime(renewDate);
// i get error at above line
updateOrganization.setRenewdate(expireDate.toDate());
organizationDAO.update(updateOrganization);

but if i format the date in the form ie, from mm/dd/yyyy to yyyy-mm-dd and send it to the java class its working fine.

How can i format the date from mm/dd/yy to yyyy-mm-dd at Java class. Input is Stringformat.

The list of valid formats for the constructor you are using are detailed in the javadoc of ISODateTimeFormat , which does not include "mm/dd/yyyy":

datetime = time | date-opt-time
time = 'T' time-element [offset]
date-opt-time = date-element ['T' [time-element] [offset]]
date-element = std-date-element | ord-date-element | week-date-element
std-date-element = yyyy ['-' MM ['-' dd]]
ord-date-element = yyyy ['-' DDD]
week-date-element = xxxx '-W' ww ['-' e]
time-element = HH [minute-element] | [fraction]
minute-element = ':' mm [second-element] | [fraction]
second-element = ':' ss [fraction]
fraction = ('.' | ',') digit+
offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])

You can parse a different format with a DateTimeFormatter (note MM in upper case for month):

DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime expireDate = fmt.parseDateTime(renewDate);

You need to parse the date using the static method parse as the constructor assumes the String is in the ISO format

The date format you need is as below

DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime expireDate = DateTime.parse( renewDate, fmt );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM