Java date formatting - java

The input string is like mentioned below
20110913T100702.631 GMT
The out put needed is in the format like this
Tuesday, September 13, 2011 17:52:PM
Can you please help me on this. (In this example the input value and the out put value are not connected those are 2 separate values)

Try:
private String formatDate() throws Exception {
DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss.SSS Z");
DateFormat outputFormat = new SimpleDateFormat("EEEEE', 'MMMMM' 'dd', 'yyyy' 'h:mm:a");
Date date = inputFormat.parse("20110913T100702.631 GMT ");
return outputFormat.format(date);
}

You need class SimpleDateFormat or DateFormat
http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/

tl;dr
ZonedDateTime.parse (
"20110913T100702.631 GMT" ,
DateTimeFormatter.ofPattern( "uuuuMMdd'T'HH:mm:ss.SSS z" )
).format(
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL , FormatStyle.SHORT )
.withLocale( Locale.US )
)
Tuesday, September 13, 2011 10:07 AM
ISO 8601
Your input string nearly complies with a format defined as a “basic” version of the standard ISO 8601 format. The word basic means minimizing the use of the separators otherwise used by the more common “expanded” version of the ISO 8601 format.
String input = "20110913T100702.631 GMT" ;
Using java.time
The other Answers use the troublesome old legacy date-time classes, now supplanted by the java.time classes.
The java.time classes use many of the standard ISO 8601 formats by default when parsing/generating strings. So often there is no need to specify a formatting pattern. But this particular basic format is not supported by default, so we must specify a formatting pattern.
DateTimeFormatter fInput = DateTimeFormatter.ofPattern ( "uuuuMMdd'T'HHmmss.SSS z" );
Parse as an ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.parse ( input, fInput );
To generate a string representing the value of the ZonedDateTime object in your desired format, you could define a specify formatting pattern. But I suggest you instead let java.time automatically localize for you.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
So…
// Generate output string
Locale locale = Locale.US; // Or Locale.CANADA_FRENCH, Locale.ITALY, etc.
DateTimeFormatter fOutput =
DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL, FormatStyle.SHORT ) // Specify format style of date portion, then time-of-day portion.
.withLocale ( locale );
String output = zdt.format ( fOutput );
Dump to console.
// Dump to console
System.out.println ( "input: " + input );
System.out.println ( "zdt.toString(): " + zdt );
System.out.println ( "output: " + output );
See this code run live at IdeOne.com.
input: 20110913T100702.631 GMT
zdt.toString(): 2011-09-13T10:07:02.631Z[GMT]
output: Tuesday, September 13, 2011 10:07 AM
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
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.

Related

I am having a problem with changing my date format

Hello guys I am having a problem in changing the date from one form to another. I have searched through stack overflow and made one solution but it is giving wrong result.
As I have date in this format:
2019-04-16 05:50:44
and I wanna convert it to this format
Apr 4
I made this code for conversion
SimpleDateFormat spf=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date newDate=spf.parse("2019-04-16 05:50:44");
spf= new SimpleDateFormat("MMM dd");
String date = spf.format(newDate);
And the result I am getting is Jan 16 and I don't know why ...
Thanks in advance
From the SimpleDateFormat documentation: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
M Month in year
m Minute in hour
So, your code should be:
SimpleDateFormat spf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date newDate=spf.parse("2019-04-16 05:50:44");
spf= new SimpleDateFormat("MMM dd");
String date = spf.format(newDate);
tl;dr
LocalDateTime // Represent a date and time-of-day but without a time zone or offset-from-UTC.
.parse(
"2019-04-16 05:50:44".replace( " " , "T" ) // Comply with ISO 8601 standard format by replacing the SPACE in the middle with a `T`.
) // Returns an immutable `LocalDateTime` object.
.format( // Generate a `String` containing text representing the value of this date-time object.
DateTimeFormatter.ofPattern( "MMM dd" , Locale.US ) // The Locale determines the human language and cultural norms used in localizing the words and formatting generated to the resulting text.
) // Returns a `String`.
Apr 16
java.time
You are using terrible date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.
Convert input to comply with ISO 8601 standard.
String input = "2019-04-16 05:50:44".replace( " " , "T" ) ;
Parse as a LocalDateTime as the input lacks indication of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
You want just the month and day, so use the MonthDay class. I suspect you could make use of this class in other parts of your code.
MonthDay md = MonthDay.from( ldt ) ;
Generate a string in localized format.
Locale locale = Locale.CANADA_FRENCH; // Or Locale.US etc.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM dd" , locale );
String output = md.format( f );
Dump to console.
System.out.println( "md.toString(): " + md );
System.out.println( "output: " + output );
md.toString(): --04-16
output: avr. 16
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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, Java SE 11, and later - 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
Most 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….

How to get full name of month from date in Java 8 while formatting

Using new Java 8 java.time API, I need to convert LocalDate and get full name of month and day. Like March (not Mar), and Monday (not Mon). Friday the 13th March should be formatted like Friday, 13 March.. not Fri, 13 Mar.
The string you are looking for is MMMM.
Source: DateTimeFormatter Javadoc
tl;dr
Use automatic localization. No need to specify formatting pattern.
localDate.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.UK )
)
Monday, 23 January 2017
LocalDate
.of( 2017 , Month.JANUARY , 23 )
.getMonth()
.getDisplayName(
TextStyle.FULL ,
Locale.CANADA_FRENCH
)
janvier
Month
Taking your title literally, I would use the handy Month enum.
LocalDate ld = LocalDate.of( 2017 , Month.JANUARY , 23 );
Month month = ld.getMonth() ; // Returns a `Month` object, whereas `getMonthValue` returns an integer month number (1-12).
Let java.time do the work of automatically localizing. To localize, specify:
TextStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
For example:
String output = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.KOREA, etc.
janvier
Date
If you want the entire date localized, let DateTimeFormatter do the work. Here we use FormatStyle rather than TextStyle.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.KOREA, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( l ) ;
String output = ld.format( f );
dimanche 23 janvier 2107
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.
Yes. Now it can be done.
LocalDate dd = new LocalDate(); //pass in a date value or params(yyyy,mm)
String ss = dd.monthOfYear.getAsText(); // will give the full name of the month
String sh = dd.monthOfYear.getAsShortText(); // shortform
import java.time.LocalDate;
Just use the getDayOfWeek()
LocalDate.of(year, month, day).getDayOfWeek().name()
You can use it as
public static String dayName(int month, int day, int year) {
return LocalDate.of(year, month, day).getDayOfWeek().name();
}

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.

Error when converting date format to another

I have a String in format "YYYY-MM-dd" and i want convert this into "MMM dd, yyyy" format.
I used bellow code to do this;
But when i convert "2014-11-18" the output is this "Sun Dec 29 00:00:00 IST 2013"
How can I solve this?
DateFormat target=new SimpleDateFormat("MMM dd, yyyy");
String P_date="2014-11-18"
Date test1 = new SimpleDateFormat("YYYY-MM-dd").parse(P_date);
String converted_date=target.format(test1);
Date test=target.parse(converted_date);
The y (lowercase Y) format means "year". Y (uppercase Y) you were using means "WeekYear".
Just use y and you should be OK:
DateFormat target=new SimpleDateFormat("MMM dd, yyyy");
String P_date="2014-11-18";
Date test1 = new SimpleDateFormat("yyyy-MM-dd").parse(P_date);
String converted_date=target.format(test1);
Date test=target.parse(converted_date);
Y returns Week year that's why you are seeing week day too. use y instead.
Date test1 = new SimpleDateFormat("yyyy-MM-dd").parse(P_date);
You can write like this
final JDateChooser startDateChooser = new JDateChooser();
startDateChooser.setDateFormatString("yyyy-MM-dd");
Date startDate = startDateChooser.getDate();
HashMap listMap = new HashMap();
listMap.put("Start Period is ", ((startDate.getYear() + 1900)+ "-" + (startDate.getMonth() + 1) + "-" +startDate.getDate()));
tl;dr
LocalDate.parse( "2014-11-18" ).format( // Parse string as `LocalDate` object, then generate a string in a certain format.
DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM )
.withLocale( Locale.US ) // Automatically localize to a locale’s human language and cultural norms.
) // Returns a String.
Details
The accepted Answer by Mureinik is correct, your formatting pattern used codes incorrectly.
Another issue is that you are interested in a date-only value, but you are using a date-with-time type.
Also, you are using troublesome old date-time classes that are now supplanted by the java.time classes.
java.time
Your YYYY-MM-DD format complies with ISO 8601 format. The java.time classes use those standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2014-11-18" ) ;
To generate a string in other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes.
You could specify a hard-coded formatting pattern. But better to soft-code by letting java.time automatically localize. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.US ; // Or Locale.CANADA_FRENCH, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l );
String output = zdt.format( f );
Nov 18, 2014
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.

formatted string to date conversion without changing format in java

I have formatted date in the form of string and i want it in date format without changing formatted pattern
here is my code
Date currDate = new Date();//Fri Oct 31 03:48:24 PDT 2014
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
String formattedDate= formatter.format(currDate);//2014-10-31 04:23:42
here am getting in "yyyy-MM-dd hh:mm:ss" format and the same format i want it in date.
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date paidDate = sdf.parse(formattedDate);
System.out.println(pattern + " " + paidDate);//Fri Oct 31 03:48:24 PDT 2014
but i am getting result as Fri Oct 31 03:48:24 PDT 2014, so pls help me to get result as 2014-10-31 04:23:42 in date format
If I understood your problem correctly:
System.out.println(pattern + " " + sdf.format(paidDate);
You seem to be under the mistaken impression that a Date object somehow encodes format of the original date. It doesn't.
So ... when you do this:
Date paidDate = sdf.parse(formattedDate);
it does not "remember" original format of the text form of the date in paidDate. And it cannot. If you want to print / unparse a Date in any format than the default one, you should use a DateFormat and call its format method. Calling toString() will just give you the date in the default format.
Try this.
System.out.println(formatter.format(paidDate));
tl;dr
Do not conflate a date-time object with a string representing its value. A date-time object has no “format”.
ZonedDateTime.now( // Instantiate a `ZonedDateTime` object capturing the current moment.
ZoneId.of( "Africa/Tunis" ) // Assign this time zone through which we see the wall-clock time used by the people of this particular region.
).format( // Generate a string representing the value of this `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) // Define a formatting pattern to match your desire.
)
2018-03-10 07:36:23
Calling ZonedDateTime::toString generates a string in standard ISO 8601 format.
2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
Date-time object has no “format”
You are confusing a date-time object in Java, or a date-time value stored in a database, with a textual representation. You can generate a string from a date-time object (or database value), but that string is separate and distinct from the value it represents. Do not conflate a string with its generating creator.
java.time
Avoid using the troublesome old date-time classes such as Date, Calendar, and SimpleDateFormat. Instead, use Instant, ZonedDateTime, and DateTimeFormatter classes, respectively.
If you have an input string such as 2014-10-31 04:23:42, replace the SPACE in the middle with a T to comply with ISO 8601 standard format. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
String input = "2014-10-31 04:23:42".replace( " " , "T" ) ;
That input lacks any indicator of time zone or offset-from-UTC. So parse as a LocalDateTime which purposely lacks any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2014-10-31T04:23:42
A LocalDateTime does not represent a moment, is not a point on the timeline. To determine an actual moment, you must supply the context of a zone or offset.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Now we have an actual moment, a point on the timeline.
To capture the current moment in UTC, use Instant.
Instant instant = Instant.now() ;
Adjust into another zone.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
I do not recommend generating strings lacking an indicator of zone/offset. But if you insist, use the built-in DateTimeFormatter and then replace the T in the middle with a SPACE to get your desired format.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2018-03-10 07:36:23.595362
If you really do not want the fractional second, then define your own formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;
2018-03-10 07:36:23
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.

Categories