SimpleDateFormat "Unparseable date" Exception - java

I am trying to parse datetime string with SimpleDateFormat.parse() but I keep receiving Unparseable date exceptions.
Here is the date format I am trying to parse: 2011-10-06T12:00:00-08:00
Here is the code I am using:
try {
String dateStr = "2011-10-06T12:00:00-08:00";
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM d, yyyy");
Date date = dateParser.parse(dateStr);
System.out.println(dateFormatter.format(date));
} catch(Exception e) {
System.out.println(e.getMessage());
}
Which returns this error: java.text.ParseException: Unparseable date: "2011-10-06T12:00:00-08:00"
As far as I know this is the correct way to use the SimpleDateFormat class but I'm not fluent in Java so I could be mistaken. Any one know what my issue is?

The timezone should be GMT-08:00 or -0800 (as Madcore Tom said). See Java docs.
In Java 7 you can use "yyyy-MM-dd'T'HH:mm:ssX"

I believe that SimpleDateFormat will not parse timezones with a colon in them (-08:00). It should be able to parse the date 2011-10-06T12:00:00-0800.
Some simple string manipulation should help you get rid of the colon.

You first need to format the value in "2011-10-06T12: 00: 00-08: 00".
Example: SimpleDateFormat dateParser = new SimpleDateFormat ("yyyy-MM-dd'T'HH: mm: ssZ");
After, create the formating for formataction desired.
Ex: SimpleDateFormat fmt = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss");
and after make parse for date.
Ex: Date date = dateParser.parse (dateFormat);
and print of date formated.
Below, one complete example.
String dataStr = "2011-10-06T12: 00: 00-08: 00";
SimpleDateFormat dataParser = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss", Locale.US);
Date date;
Try {
date = dataParser.parse (dataStr);
System.out.println (dateFormatter.format (date));
} cath (ParseException e) {
}

tl;dr
OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" )
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ) // Or Locale.CANADA_FRENCH and such.
)
Oct 6, 2011
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
You input string is in a format that complies with the ISO 8106 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Parse as an OffsetDateTime because your input strings includes an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" ) ;
odt.toString(): 2011-10-06T12:00-08:00
Generate a string in your desired format. Let java.time automatically localize rather than hard-code formatting patterns.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ); // Or Locale.CANADA_FRENCH and such.
String output = odt.format( f );
output: Oct 6, 2011
When seralizing a date-time value as text, use the standard ISO 8601 formats rather than a localized format.
String output = odt.toLocalDate().toString() ;
2011-10-06
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Try with
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

For a date format like 2013-06-28T00:00:00+00:00, this code should work:
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

I am sure most of you got frustrated from the fact that SimpleDateFormat can not handle ISO8601 format. Here is my little trick to solve this nuisance.
Create a list of Know format you know that you will use for your application and apply SimpleDateFormat to the list. Now, in your formatDate() method, simple try all your known format and trap the Exception, then if still did not have a date, just use
Date d = javax.xml.bind.DatatypeConverter.parseDateTime("2013-06-28T00:00:00+00:00").getTime();
if (d == null)
try {
SimpleDateFormater ...
}
to try it and see if that work. For more info Simple trick to convert Date format with timezone in Java!

I'd strongly recommend using JodaTime for this sort of thing.
You're trying to parse an ISO Date format, and Joda does that 'out of the box', and will give you plenty of other benefits too.
I long ago gave up trying to get the standard JDK data classes to do helpful things.

Related

How to convert string to date object in java [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 4 years ago.
I have a string in this format
String oldstring = "Mar 19 2018 - 14:39";
How to convert this string to java object so that I get time and mins from date object.
I have tried like this,
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateEg {
public static final void main(String[] args) {
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");
String oldstring = "Mar 19 2018 - 14:39";
String time = localDateFormat.format(oldstring);
System.out.println(time);
}
}
But getting error, saying Cannot format given Object as a Date
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.base/java.text.DateFormat.format(DateFormat.java:332)
at java.base/java.text.Format.format(Format.java:158)
at DateEg.main(DateEg.java:9)
Is it possible to parse this string format in java?
User proper formatter with your code to parse string mentioned below
SimpleDateFormat localDateFormat = new SimpleDateFormat("MMM dd yyyy - HH:mm");
String oldstring = "Mar 19 2018 - 14:39";
Date date=localDateFormat.parse(oldstring);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
tl;dr
LocalDateTime.parse( // Parse as a `LocalDateTime` because the input lacks indication of zone/offset.
"Mar 19 2018 - 14:39" ,
DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , Locale.US )
) // Returns a `LocalDateTime` object.
.toLocalTime() // Extract a time-of-day value.
.toString() // Generate a String in standard ISO 8601 format.
14:39
java.time
The modern approach uses the java.time classes.
Define a formatting pattern to match your input. Specify Locale to determine human language and cultural norms used in parsing this localized input string.
String input = "Mar 19 2018 - 14:39" ;
Locale locale = Locale.US ; // Specify `Locale` to determine human language and cultural norms used in parsing this localized input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , locale ) ;
Parse as a LocalDateTime because the input lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f );
Extract the time-of-day value, without a date and without a time zone, as that is the goal of the Question.
LocalTime lt = ldt.toLocalTime();
ldt.toString(): 2018-03-19T14:39
lt.toString(): 14:39
ISO 8601
The format of your input is terrible. When serializing date-time values as text, always use standard ISO 8601 formats.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings. You can see examples above in this Answer.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try using this, this should work:
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM dd yyyy - HH:mm");
LocalDateTime dt = formatter.parse(oldstring);`
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
String time = timeFormat.format(dt).toString();`
If you can use an external library, the Apache Common DateUtils provides many utility classes that you can use to work on dates.
In order to parse your string to an object you can use for instance:
public static Date parseDate(String str, Locale locale, String... parsePatterns) throws ParseException
Parses a string representing a date by trying a variety of different
parsers, using the default date format symbols for the given locale.
The parse will try each parse pattern in turn. A parse is only deemed
successful if it parses the whole of the input string. If no parse
patterns match, a ParseException is thrown.
The parser will be lenient toward the parsed date.
Parameters:str - the date to parse, not nulllocale - the locale whose
date format symbols should be used. If null, the system locale is used
(as per parseDate(String, String...)).parsePatterns - the date format
patterns to use, see SimpleDateFormat, not nullReturns:the parsed
dateThrows:IllegalArgumentException - if the date string or pattern
array is nullParseException - if none of the date patterns were
suitable (or there were none)Since:3.2

getTimeInMillis() in java [duplicate]

I have a problem in converting the date in java, don't know where i am going wrong...
String dateStr = "2011-12-15";
String fromFormat = "yyyy-mm-dd";
String toFormat = "dd MMMM yyyy";
try {
DateFormat fromFormatter = new SimpleDateFormat(fromFormat);
Date date = (Date) fromFormatter.parse(dateStr);
DateFormat toformatter = new SimpleDateFormat(toFormat);
String result = toformatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
Input date is 2011-12-15 and I am expecting the result as "15 December 2011", but I get it as "15 January 2011"
where am I going wrong?
Your fromFormat uses minutes where it should use months.
String fromFormat = "yyyy-MM-dd";
I think the fromFormat should be "yyyy-MM-dd".
Here is the format:
m == Minute in Hour
M == Month in Year
More: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
From format should be:
String fromFormat = "yyyy-MM-dd"
Look at the javadoc of SimpleDateFormat and look at what the m represents. Not months as you think but minutes.
String fromFormat = "yyyy-MM-dd";
m in SimpleDateFormat stands for minutes, while M stands for month. Thus your first format should be yyyy-MM-dd.
tl;dr
LocalDate.parse( "2011-12-15" ) // Date-only, without time-of-day, without time zone.
.format( // Generate `String` representing value of this `LocalDate`.
DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG ) // How long or abbreviated?
.withLocale( // Locale used in localizing the string being generated.
new Locale( "en" , "IN" ) // English language, India cultural norms.
) // Returns a `DateTimeFormatter` object.
) // Returns a `String` object.
15 December 2011
java.time
While the accepted Answer is correct (uppercase MM for month), there is now a better approach. The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
Your input string is in standard ISO 8601 format. So no need to specify a formatting pattern for parsing.
LocalDate ld = LocalDate.parse( "2011-12-15" ); // Parses standard ISO 8601 format by default.
Locale l = new Locale( "en" , "IN" ) ; // English in India.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG )
.withLocale( l );
String output = ld.format( f );
Dump to console.
System.out.println( "ld.toString(): " + ld );
System.out.println( "output: " + output );
ld.toString(): 2011-12-15
output: 15 December 2011
See live code in IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Well this may not be your case but may help someone. In my case after conversion, day of month and month set 1. So whatever date is, after conversion i get 1 jan which is wrong.
After struggling i found that in date format i have used YYYY instead of yyyy. When i changed all caps Y to y it works fine.

How convert String to dateTime with milliseconds

How convert this string to dateTime?
2016-01-09 21:04:56.0
I tried
private Date getDate(CallDetail callDetail) {
Date date = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
date = simpleDateFormat.parse(callDetail.getStarttime());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
But I have error:
Unparseable date: "2016-01-09 21:04:56.0"
I do not know how trim .0
Your format string has to represent the string you want to parse.
E.g. if you want to parse 25.12.2015 your format string has to be "dd.MM.yyyy".
With that being said, your format string to parse the given date should be "yyyy-MM-dd HH:mm:ss:S"
If you just want to get rid of the milliseconds you could either parse the date and format it it afterwards:
String toParse = "2016-01-09 21:04:56.0";
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date newDate = sdfIn.parse(toParse);
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
toParse = sdfOut.format(newDate);
or just cut off the milliseconds with substring():
String toParse = "2016-01-09 21:04:56.0";
toParse = toParse = toParse.substring(0, toParse.lastIndexOf("."));
Try using below format "yyyy-MM-dd hh:mm:ss.S"
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.S");
Date date = simpleDateFormat.parse("2016-01-09 21:04:56.0");
System.out.println(date);
}
output
Sat Jan 09 21:04:56 IST 2016
The modern way is with the java.time classes and standard ISO 8601 formats.
ISO 8601
The ISO 8601 standard defines many formats for representing date-time values as text. For a date with time-of-day, the format is YYYY-MM-DDTHH:MM:SS.s.
The java.time classes use these standard formats by default when parsing and generating strings.
Your input string can be made to comply easily. Replace the SPACE in the middle with a T.
String input = "2016-01-09 21:04:56.0".replace( " " , "T" );
LocalDateTime
Your input string lacks any indication of time zone or offset-from-UTC. So we parse as a LocalDateTime object.
LocalDateTime ldt = LocalDateTime.parse( input );
Your goal seems to be generating a string of this date-time value without the fractional second if zero. The LocalDateTime class does this by default, printing zero, three, six, or nine digits of fractional second, the least needed.
String output = ldt.toString();
2016-01-09T21:04:56
For your desired format, replace the T with a SPACE.
String output2 = output.replace( "T" , " " );
A LocalDateTime intentionally lacks any time zone. As such, it does not represent a moment on the timeline. That requires the context of a time zone.
Truncation
If you want to get rid of the fractional second, truncate.
LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Convert string to appropriate date with timezone java

I am Having Date with it's timezone, I want to convert it to another Timezone, E.g. I have Date '3/15/2013 3:01:53 PM' which is in TimeZone 'GMT-06:00'. I want to convert this in 'GMT-05:00' timezone. I have search lot, and I am confuse about How actually Date is working. How to Apply timezone to date. I have try with SimpleDateFormat, Calender and also with offset.
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa XXX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM -06:00");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = df.format(dt);
System.out.println(newDateString);
It returns output
03/15/2013 09:01:53 AM Z.
I guess it should be
03/15/2013 09:01:53 PM Z, because time in 'GMT-06:00' timezone, so it should be HH+6 to get time in GMT. I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.Please Help me with example. Thanks in advance.
EDIT :
I am converting the string into date using SimpleDateFormat
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa");
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM");
} catch (ParseException e) {
e.printStackTrace();
}
Now, as you say, I specify to Calendar that my date is in 'GMT-06:00' timezone and set my date,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"));
cal.setTime(dt);
Now, I am telling calendar that I want date in 'GMT'
cal.setTimeZone (TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());
OutPut:
Fri Mar 15 03:01:53 CDT 2013
Please know me if i am going wrong.
You need TWO format objects, one for parsing and another one for printing because you use two different timezones, see here:
// h instead of H because of AM/PM-format
DateFormat parseFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
Date dt = null;
try {
dt = parseFormat.parse("3/15/2013 3:01:53 PM -06:00");
}catch (ParseException e) {
e.printStackTrace();
}
DateFormat printFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
printFormat.setTimeZone(TimeZone.getTimeZone("GMT-05"));
String newDateString = printFormat.format(dt);
System.out.println(newDateString);
Output: 3/15/2013 04:01:53 PM -05:00
If you want HH:mm:ss (24-hour-format) then you just replace
hh:mm:ss aaa
by
HH:mm:ss
in printFormat-pattern.
Comment on other aspects of question:
A java.util.Date has no internal timezone and always refers to UTC by spec. You cannot change it inside this object. A timezone conversion is possible for the formatted string, however as demonstrated in my code example (you wanted to convert to zone GMT-05).
The question then switches to the new requirement to print the Date-object in ISO-format using UTC timezone (symbol Z). This can be done in formatting by replacing the pattern with "yyyy-MM-dd'T'HH:mm:ssXXX" and explicitly setting the timezone of printFormat to GMT+00. You should clarify what you really want as formatted output.
About java.util.GregorianCalendar: Setting the timezone here is changing the calendar-object in a programmatical way, so it affects method calls like calendar.get(Calendar.HOUR_OF_DAY). This has nothing to do with formatting however!
tl;dr
OffsetDateTime.parse(
"3/15/2013 3:01:53 PM -06:00" ,
DateTimeFormatter.ofPattern( "M/d/yyyy H:mm:ss a XXX" )
).withOffsetSameInstant(
ZoneOffset.of( -5 , 0 )
)
2013-03-15T15:01:53-06:00
java.time
The Answer by Hochschild is correct but uses outdated classes. The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the modern java.time classes.
Parse your input string as a OffsetDateTime as it contains an offset-from-UTC but not a time zone.
String input = "3/15/2013 3:01:53 PM -06:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/yyyy h:mm:ss a XXX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2013-03-15T15:01:53-06:00
Tip: Save yourself some hassle and use the ISO 8601 formats when exchanging date-time data as text. The java.time classes use these standard formats by default when parsing/generating strings.
Apparently you want to see the same moment as viewed by the people elsewhere using a different offset-from-UTC.
ZoneOffset offset = ZoneOffset.of( -5 , 0 ) ;
OffsetDateTime odt2 = odt.withOffsetSameInstant( offset ) ;
We see the offset changes from 6 to 5, and the hour-of-day changes accordingly from 15 to 16. Same simultaneous moment, different wall-clock time.
odt2.toString(): 2013-03-15T16:01:53-05:00
Generating strings
I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.
I suggest you always include some indication of the offset or zoneunless your are absolutely certain the user understands from the greater context.
Your format is nearly in standard ISO 8601 format. You could define your own formatting pattern, but I would just do string manipulation to replace the T in the middle with a SPACE.
String output = odt2.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2013-03-15 16:01:53
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to convert date from MM/YYYY to MM/DD/YYYY in Java

I want to convert date from MM/YYYY to MM/DD/YYYY, how i can do this using SimpleDateFormat in Java? (Note: DD can be start date of that month)
please go through the http://download.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html following link for more clarity.
One way of implementation i have in my mind is :
String yourDate = <yourDate>
DateFormat dateFormat= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date= new Date();
date = (Date)dateFormat.parse(yourDate);
//String dateString= dateFormat.format(date);
/*Print your date*/
Please go through this link SimpleDateFormat
try {
String str_date = "01/11";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/yyyy");
date = (Date) formatter.parse(str_date);
formatter = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today is " + formatter.format(date));
} catch (ParseException e) {
System.out.println("Exception :" + e);
}
The simplest approach is using string manipulation.
String date1 = "12/2010";
String date2 = date1.replace("/","/01/");
tl;dr
YearMonth.parse(
"12/2016" ,
DateTimeFormatter.ofPattern( "MM/uuuu" ) )
)
.atDay( 1 )
.format( DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ) // 12/01/2016
java.time
Java now includes the YearMonth class to represent exactly this kind of value, a month and a year without a day-of-month.
The default format for parsing/generating strings of a month-year is YYYY-MM. That format is defined as part of the ISO 8601 format. The java.time classes use ISO 8601 formats by default.
Your input string has alternate format so we must specify a formatting pattern.
String input = "12/2016" ; // December 2016.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" );
YearMonth ym = YearMonth.parse( input , f );
See the results by calling toString.
String output = ym.toString();
2016-12
Specify a day-of-month to create a LocalDate instance. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = ym.atDay( 1 );
You can let the class figure out the last day of the month. Remember that February varies in length for Leap Year. The YearMonth class knows how to handle Leap Year.
LocalDate ld = ym.atEndOfMonth();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
FYI, Java has a similar class, MonthDay.

Categories