display Java.util.Date in a specific format
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
convert java.util.Date to java.util.Date with different formating in JAVA
tl;dr
Convert from legacy class to modern class. Adjust from UTC to a time zone. Generate text in standard ISO 8601. We omit the context of time zone or offset in our output because you so requested, against my recommendation.
myJavaUtilDate
.toInstant()
.atZone( ZoneId.of( "Asia/Kolkata" ) )
.truncatedTo( ChronoUnit.MINUTES )
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
I expect using UTC and including the offset would be wiser.
myJavaUtilDate
.toInstant()
.toString()
Details
Date-time objects do not have a format, only text has a format.
Use java.time classes, never java.util.Date
.
Convert your legacy Date
object to its modern replacement, java.time.Instant
.
Instant instant = myJUDate.toInstant() ;
Adjust from UTC to your desired time zone.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Apparently you do not care about the the second of minute. So let’s truncate that to zero seconds.
ZonedDateTime zdt = zdt.truncatedTo( ChronoUnit.MINUTES ) ;
Generate text in your desired format. Java comes bundled with a formatter already defined for your format.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
I showed that format because asked. But I do not recommend it. That format fails to indicate a time zone or offset-from-UTC. So if it says noon, the reader does not know if that means noon in Tokyo Japan , noon in Toulouse France , or noon in Toledo Ohio Us — three very different moments, several hours apart.
When communicating a moment, a specific point on the timeline, textually it is usually best to do so in UTC. And use ISO 8601 standard formats. Commonly a Z
is placed on the end to indicate UTC, an offset of zero hours-minutes-seconds.
Instant instant = zdt.toInstant() ;
String output = instant.toString() ;
Printing out datetime in a specific format in Java?
Approach 1: Using java.time.LocalDateTime. (Strongly Preferred)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
Approach 2: Using java.util.Date.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
Approach 3: Using java.util.Calendar.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
Date
is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).
It has no concept of format.
Java 8+
LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);
Outputs...
05-11-2018
2018-05-11
2018-05-11T17:24:42.980
Java 7-
You should be making use of the ThreeTen Backport
Original Answer
For example...
Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);
Outputs...
Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013
None of the formatting has changed the underlying Date
value. This is the purpose of the DateFormatter
s
Updated with additional example
Just in case the first example didn't make sense...
This example uses two formatters to format the same date. I then use these same formatters to parse the String
values back to Date
s. The resulting parse does not alter the way Date
reports it's value.
Date#toString
is just a dump of it's contents. You can't change this, but you can format the Date
object any way you like
try {
Date myDate = new Date();
System.out.println(myDate);
SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);
// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}
Which outputs...
Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013
Also, be careful of the format patterns. Take a closer look at SimpleDateFormat
to make sure you're not using the wrong patterns ;)
How to correctly create a date with a specific format?
Try like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date c= sdf.parse("2015-05-26");
String date=sdf.format(c);
System.out.println(date);
To format the current date in yyyy-MM-dd format you can try like this
Date date = new Date();
String str = new SimpleDateFormat("yyyy-MM-dd").format(date);
Kindly refer SimpleDateFormat
Is it possible to get java.util.Date object with specific format?
Is it possible to get Date object with specific format?
No. Date
doesn't have any format. It represents the number of milliseconds since epoch. You only get the formatted string using SimpleDateFormat
, which you already did.
Printing Date
invokes the overridden Date#toString()
method, which uses a default format, in which every Date
is printed.
Here's how Date#toString()
source looks like:
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
.... // some more code
}
So the format used is "EEE MMM dd HH:mm:ss zzz yyyy"
How to convert String to Date with a specific format in java
The class Date
will always contain both date a nd time information, since it represents an instant in time.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}
As you can see, hours, minutes, seconds and millis get all set to 0.
If you later want to output the date in string format, you need to use the DateFormat#format(Date)
method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}
If you'd rather store only date information, you could use the java.time
package and make use of LocalDate
.LocalDate
stores only date information, since it does not represent an instant, rather a triple of year, month and date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParsingLocalDate {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}
Related Topics
Difference Between Hashmap, Linkedhashmap and Treemap
Do We Have Any Generic Function to Check If Page Has Completely Loaded in Selenium
Difference Between Inheritance and Composition
How to Make a JPA Onetoone Relation Lazy
Getting the Name of the Currently Executing Method
Java - Get Pixel Array from Image
Bringing Jfilechooser on Top of All Windows
Spring - @Transactional - What Happens in Background
How to Efficiently Remove Duplicates from an Array Without Using Set
How to Add an Image to a Jpanel
How to Implement Rest Token-Based Authentication With Jax-Rs and Jersey
Difference Between Declaring Variables Before or in Loop
How to Tell Gradle to Use Specific Jdk Version
How to Determine Day of Week by Passing Specific Date
Placing Component on Glass Pane
How to Import an Existing X.509 Certificate and Private Key in Java Keystore to Use in Ssl