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.
Related
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
this is the code which returns Date but at the client side i am getting
2016-12-26 14:18:57.0 at the client side . what is the possible solution .. I am using node.js at the client side. But I think it has nothing to do with this problem . I WANT TO REMOVE THIS 0
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
return date != null;
Try to set proper format in SimpleDateFormat constructor. Something like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String value = "2016-12-26 14:18:57";
Date date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
System.out.println("not equals");
}
System.out.println("date = " + date);
You are not giving a format pattern string to the SimpleDateFormat constructor, so it uses some default pattern. The solution is to provide a proper format string.
The formatting can be done like this:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS")
which would result e.g. in
29.02.2016 23:01:15.999
You want to omit the S format symbols (milliseconds) in the format string. E.g.:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss")
Of course you need to change this example to your format needs. Play a bit with the order and number of symbols, confer the docs.
tl;dr
LocalDateTime.parse(
"2016-12-26 14:18:57.0".replace( " " , "T" )
)
.truncatedTo( ChronoUnit.SECONDS )
.toString()
.replace( "T" , " " )
Avoid legacy date-time classes
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
ISO 8601
First replace the SPACE in the middle of your input string to make it comply with the standard ISO 8601 format.
String input = "2016-12-26 14:18:57.0".replace( " " , "T" );
LocalDateTime
Parse as a LocalDateTime given that your input string lacks any indication of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input );
Generate a String by simply calling toString. By default an ISO 8601 format is used to create the String. If the value has no fractional second, no decimal mark nor any fractional seconds digits appear.
String output = ldt.toString ();
ldt.toString(): 2016-12-26T14:18:57
If you dislike the T in the middle, replace with a SPACE.
output = output.replace( "T" , " " );
2016-12-26 14:18:57
If your input might carry a fractional second and you want to delete that portion of data entirely rather than merely suppress its display, truncate the LocalDateTime object.
LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ); // Truncate any fraction of a second.
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.
I want to parse a date, which was created with a specific timezone, convert it to a format and return it. The conversion works but the timezone offset is always set to +0000 with the time difference being added/subtracted as necessary. How can I get it to format and keep the offset correct?
I expect this: 2012-11-30T12:08:56.23+07:00
But get this: 2012-11-30T05:08:56.23+00:00
Implementation:
public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSZZ";
public static String formatDateToISO8601Standard(Date date) {
DateTime dateTime = new DateTime(date);
DateTimeFormatter df = DateTimeFormat.forPattern(ISO_8601_DATE_FORMAT);
return dateTime.toString(df);
}
Test class:
private static final String DATE_WITH_TIMEZONE = "30 11 2012 12:08:56.235 +0700";
private static final String EXPECTED_DATE_WITH_TIMEZONE = "2012-11-30T12:08:56.23+07:00";
#Test public void testFormattingDateWithSpecificTimezone() throws Exception {
String result = JodaDateUtil.formatDateToISO8601Standard(createDate(DATE_WITH_TIMEZONE));
assertEquals("The date was not converted correctly", EXPECTED_DATE_WITH_TIMEZONE, result); }
private Date createDate(String dateToParse) throws ParseException {
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.parseDateTime(dateToParse);
Date date = temp.toDate();
return date; }
Basically, once you parse the date string [in your createDate() method] you've lost the original zone. Joda-Time will allow you to format the date using any zone, but you'll need to retain the original zone.
In your createDate() method, the DateTimeFormatter "df" can return the zone that was on the string. You'll need to use the withOffsetParsed() method. Then, when you have your DateTime, call getZone(). If you save this zone somewhere or somehow pass it to your formatting routine, then you can use it there by creating a DateTimeFormatter "withZone" and specifying that zone as the one you want on the format.
As a demo, here's some sample code in a single method. Hopefully, it'll help change your code the way you want it to run.
public static void testDate()
{
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.withOffsetParsed().parseDateTime("30 11 2012 12:08:56.235 +0700");
DateTimeZone theZone = temp.getZone();
Date date = temp.toDate();
DateTime dateTime = new DateTime(date);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
DateTimeFormatter df3 = df2.withZone(theZone);
System.out.println(dateTime.toString(df2));
System.out.println(dateTime.toString(df3));
}
tl;dr
OffsetDateTime.parse (
"30 11 2012 12:08:56.235 +0700" ,
DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US )
).toString()
2012-11-30T12:08:56.235+07:00
Details
The accepted Answer is correct. As soon as you convert to a java.util.Date object, you lose time zone information. This is complicated by the fact that java.util.Date::toString confusingly applies a current default time zone when generating the String.
Avoid using these old date-time classes like java.util.Date. They are poorly-designed, confusing, and troublesome. Now legacy, supplanted by the java.time project. So too is the Joda-Time project now supplanted by the java.time classes.
java.time
Parse that input string as a OffsetDateTime object as it includes an offset-from-UTC but lacks a time zone. Call DateTimeFormatter.ofPattern to specify a custom format matching your input string. Pass that formatter object to OffsetDateTime.parse.
String input = "30 11 2012 12:08:56.235 +0700" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
odt:toString(): 2012-11-30T12:08:56.235+07:00
To see the same moment in UTC, extract an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = odt.toInstant();
instant.toString(): 2012-11-30T05:08:56.235Z
You can apply any time zone through which you want to view the same moment, the same point on the timeline.
ZonedDateTime zdtKolkata = odt.toInstant ().atZone ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata.toString(): 2012-11-30T10:38:56.235+05:30[Asia/Kolkata]
No need to mix in the old date-time classes at all. Stick with java.time. If you must use some old code not yet updated to java.time types, look to new methods added to the old classes to convert to/from java.time.
The equivalent of java.util.Date is Instant, both being a count-since-epoch of 1970-01-01T00:00:00Z in UTC. But beware of data-loss as the java.time classes support nanosecond resolution but the old classes are limited to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant );
Live code
See live working 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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
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.
Try this.
ISODateTimeFormat.dateTimeParser().parseDateTime(dateString),
then convert that to the format you desire.
Use the format
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSZZ")
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.
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.