Since the java.util.Date object stores Date as 2014-01-24 17:33:47.214, but I want the Date format as 2014-01-24 17:33:47. I want to remove the milliseconds part.
I checked a question related to my question...
How to remove sub seconds part of Date object
I've tried the given answer
long time = date.getTime();
date.setTime((time / 1000) * 1000);
but I've got my result Date format as 2014-01-24 17:33:47.0. How can I remove that 0 from my Date format???
tl;dr
Lop off the fractional second.
myJavaUtilDate.toInstant() // Convert from legacy class to modern class. Returns a `Instant` object.
.truncatedTo( ChronoUnit.SECONDS ) // Generate new `Instant` object based on the values of the original, but chopping off the fraction-of-second.
Hide the fractional second, when generating a String.
myJavaUtilDate.toInstant() // Convert from legacy class to modern class. Returns a `Instant` object.
.atOffset( ZoneOffset.UTC ) // Return a `OffsetDateTime` object.
.format( DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ). // Ask the `OffsetDateTime` object to generate a `String` with text representing its value, in a format defined in the `DateTimeFormatter` object.
Avoid legacy date-time classes
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Instant
Convert your old java.util.Date object to a java.time.Instant by calling new method added to the old class.
Instant instant = myJavaUtilDate.toInstant() ;
Truncate
If you want to change value of the data itself to drop the fraction of a second, you can truncate. The java.time classes use immutable objects, so we generate a new object rather than alter (mutate) the original.
Instant instantTruncated = instant.truncatedTo( ChronoUnit.SECONDS );
Generating string
If instead of truncating you merely want to suppress the display of the fractional seconds when generating a string representing the date-time value, define a formatter to suit your needs.
For example, "uuuu-MM-dd HH:mm:ss" makes no mention of a fractional second, so any milliseconds contained in the data simply does not appear in the generated string.
Convert Instant to a OffsetDateTime for more flexible formatting.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC )
String output = odt.format( f );
Time zone
Note that your Question ignores the issue of time zone. If you intended to use UTC, the above code works as both Date and Instant are in UTC by definition. If instead you want to perceive the given data through the lens of some region’s wall-clock time, apply a time zone. Search Stack Overflow for ZoneId and ZonedDateTime class names for much more info.
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.
Basic answer is, you can't. The value returned by Date#toString is a representation of the Date object and it carries no concept of format other then what it uses internally for the toString method.
Generally this shouldn't be used for display purpose (except for rare occasions)
Instead you should be using some kind of DateFormat
For example...
Date date = new Date();
System.out.println(date);
System.out.println(DateFormat.getDateTimeInstance().format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(date));
System.out.println(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(date));
Will output something like...
Thu Jan 30 16:29:31 EST 2014
30/01/2014 4:29:31 PM
30/01/14 4:29 PM
30/01/2014 4:29:31 PM
30 January 2014 4:29:31 PM
If you get really stuck, you can customise it further by using a SimpleDateFormat, but I would avoid this if you can, as not everybody uses the same date/time formatting ;)
You can use SimpleDateFormatter. Please see the following code.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
Date now = date.getTime();
System.out.println(formatter.format(now));
Truncate to Seconds (no milliseconds), return a new Date:
public Date truncToSec(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MILLISECOND, 0);
Date newDate = c.getTime();
return newDate;
}
Use Apache's DateUtils:
import org.apache.commons.lang.time.DateUtils;
...
DateUtils.truncate(new Date(), Calendar.SECOND)
You can use the SimpleDateFormat class to format the date as necessary. Due to the diversity of possible combinations, I will simply include the documentation link here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your code will look something similar to the following:
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(date));
Just for the record, the accepted answer given at the post you linked works:
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("S");
Date d = new Date();
System.out.println(df.format(d));
Calendar c = Calendar.getInstance();
c.set(Calendar.MILLISECOND, 0);
d.setTime(c.getTimeInMillis());
System.out.println(df.format(d));
}
Please try the following date formatter:
import java.text.*;
SimpleDateFormat tmp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
System.out.println(tmp.format(date));
Related
I converted a date string to Date by SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(DateinString).
Here instead of converting to UTC it is converting to my Local TimeZone. I checked it by displaying this parsed date through format method of DateFormat.
So I have to re format it back to UTC.Now when I am trying to display this parsed date to UTC TimeZone through the same format method, it is still displaying in local TimeZone. Following is my code to format the parsed date to UTC-
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(alreadyParsedDateTime); //
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(cal.getTime()));
My sample date string is "2015-12-23T15:00:00-0800"
After parse -- alreadyParsedDateTime.toString():: Thu Dec 24 04:30:00 IST 2015
After parse --
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(alreadyParsedDateTime)):: 2015-12-24T04:30:00
After the above mentioned re format of the parsed date to UTC --
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(cal.getTime())):: 2015-12-24T04:30:00
Expected date format is:: 2015-12-23T23:00:00
I don't know why the format method not working in an expected way or there is any trick to do the same. Kindly help..
There are two different topics here; parsing and formatting.
1. Parsing
SimpleDateFormat.parse() will try to parse the timezone from the supplied date string. If the date string you are parsing does not include an explicit timezone, then the "default" timezone on the SimpleDateFormat object will be used. You can set the default time zone with the setTimeZone() method. Please see the API docs for SimpleDateFormat.parse() and DateFormat.setTimeZone() for reference.
Here is an example that shows how the parsing is influenced by the timezone set with setTimeZone():
String dateString = "2015.12.10 13:58:18";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date1 = sdf1.parse(dateString);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("EST"));
Date date2 = sdf2.parse(dateString);
// Shows that the parsing honours time zone -- will print:
// Thu Dec 10 14:58:18 CET 2015 (original date was parsed as GMT)
// Thu Dec 10 19:58:18 CET 2015 (original date was parsed as EST)
System.out.println(date1);
System.out.println(date2);
2. Formatting
Assuming that the date has been parsed correctly, then your problem is with the formatting. You need to set the timezone for the actual SimpleDateFormat object that you are using for formatting. I modified your code to do this and it will now print what you expet:
Calendar cal = Calendar.getInstance();
cal.setTime(alreadyParsedDateTime);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf3.setTimeZone(TimeZone.getTimeZone("UTC"));
// Prints: 2015-12-23T23:00:00 for your example date string
System.out.println(sdf3.format(cal.getTime()));
tl;dr
Current moment in UTC.
Instant.now() // Capture current moment in UTC.
.toString() // Generate string in standard ISO 8601 format.
2018-02-11T22:13:28.650328Z
Adjust into another time zone.
instant.atZone( // Apply a `ZoneId` to `Instant` object to get a `ZonedDateTime` object.
ZoneId.of( "Pacific/Auckland" )
).toString()
2018-02-12T11:13:28.650328+13:00[Pacific/Auckland]
Or capture current moment directly into that zone.
ZonedDateTime.now( // Capture current moment as seen on the wall-clock time of the people in a particular region.
ZoneId.of( "Pacific/Auckland" )
).toString() // Generate string in standard ISO 8601 format, wisely extended by appending the name of the time zone in square brackets.
2018-02-12T11:13:28.650328+13:00[Pacific/Auckland]
Details
The Answer by Grodriguez is correct but outdated.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
Your input string complies with the ISO 8601 formatting standard. The java.time classes use these formats by default when parsing/generating strings. So no need to specify a formatting pattern.
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).
Capture the current moment in UTC.
Instant instant = Instant.now() ; // Current moment in UTC.
To view that same simultaneous moment through the lens of a wall-clock time used by the people of another region (time zone), apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Note that we are working with smart objects here, not dumb strings. Do not conflate the date-time objects with mere strings that may represent their values textually.
If you want to generate a String in standard ISO 8601 format, call the toString method.
String outputA = instant.toString() ;
String outputB = zdt.toString() ;
To generate strings in other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Both are covered extensively on Stack Overflow, so search for more info.
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.
I used the below code where I've printed the modified GMT date in String & in Date format, it's giving me two different values.
Date initial = new Date();
DateFormat dateFormatter = DateFormat.getInstance();
dateFormatter.setTimeZone (TimeZone.getTimeZone("UTC"));
String gmtS = dateFormatter.format(initial);
Date gmt = dateFormatter.parse(gmtS);
System.out.println("Data type is Date = " + gmt);
System.out.println("Data type is String "+gmtS);
Output
gtm where value id of type Date = Thu Jul 03 23:15:00 EDT 2014
gmtS where value id of type String = 7/4/14 3:15 AM
But I want to see the value (7/4/14 3:15 AM) as a Date type.
Any help is really appreciated.
When you output a Date by calling toString() (which is what System.out.println("Data type is Date = " + gmt); does) you will get that Date according to the system time zone, because that is what Date.toString() returns.
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
where:
...
zzz is the time zone (and may reflect daylight saving time). Standard time
zone abbreviations include those recognized by the method parse. If time
zone information is not available, then zzz is empty - that is, it
consists of no characters at all.
So, to get the output you expect use your dateFormatter to format it again.
String gmtS = dateFormatter.format(initial);
Date gmt = dateFormatter.parse(gmtS);
System.out.println("Data type is Date = " + dateFormatter.format(gmt));
tl;dr
Instant.now().toString()
2019-02-07T19:15:29.123456Z
Avoid legacy date-time classes
You are using date-time classes that are terribly troublesome, with many flaws in design.
First, you should know that java.util.Date represents a moment in UTC, always in UTC by definition. But its toString method tells a lie, dynamically applying the JVM’s current default time zone while generating the text representing the moment in the Date object.
java.time
The modern approach uses the java.time classes.
Instant
For a moment in UTC, use Instant. Like java.time.Date it represents a moment always in UTC (but with a finer resolution of nanoseconds versus milliseconds). Indeed, you can convert easily back-and-forth between Date and Instant by using new methods added to the old class.
Unlike toString on Date, the toString method on Instant always tells the truth. The method generates text in standard ISO 8601 format. The T in the middle separates the date portion from the time portion. The Z on the end is short for UTC and is pronounced “Zulu”.
Instant.now().toString(): 2019-01-23T12:34:56.123456789Z
OffsetDateTime
The Instant class is a basic building-block class in java.time, with limited functionality. If you want more flexible formatting, use the OffsetDateTime class with the offset set to UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
Or skip the Instant class.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
To generate text representing the value of the OffsetDateTime object, use the DateTimeFormatter class. Search Stack Overflow as this has been covered many many times already.
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, 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….
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 achieve a similar operation in java:
time = "2014-05-19 13:36:05"
interval = "60 (seconds)"
time - interval = "2014-05-19 13:35:05"
What's the best approach to express this in Java given the following constraints:
The datetime is a formated string.
The interval is an integer.
The calculated time should be also a datetime formatted string.
You should work with "Date" objects, which basically represent an instance in time (number of milliseconds since Unix epoch) when doing the subtraction. Once you have a "Date" Object you can use "getTime" method (http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime()) to get this milliseconds value, and subtract 60 seconds (make sure to work with milliseconds not seconds!), and create a new "Date" with that resulting value.
This is one approach. There are many, Joda library is also quite popular. It has a method to subtract milliseconds from its date representation, http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#minusSeconds(int).
Try using the joda-time library.
Here is the class to parse the date string.
Use:
dateTime.minusSeconds(int sec);
method to substract your interval.
java.time
The modern way is with java.time classes.
Do not conflate a point-in-time (a moment) with a span-of-time (a duration). Avoid representing a span-of-time using time-of-day notation as that creates ambiguity and confusion. Use standard ISO 8601 formatted strings to represent a duration: PnYnMnDTnHnMnS.
Do not conflate a date-time value (object) with a String representation. A date-time object can parse or generate a String but is distinct and separate from the String.
The java.time framework is rich with various date-time classes. Use these to represent your data as objects rather than mere numbers and strings.
The java.time classes use standard ISO 8601 formatted strings by default.
String input = "2014-05-19T13:36:05" ;
LocalDateTime ldt = LocalDateTime.parse( input );
Duration d = Duration.ofSeconds( 60 );
LocalDateTime later = ldt.plus( d );
ld.toString(): 2014-05-19T13:36:05
d.toString(): PT1M
later.toString(): 2014-05-19T13:37:05
See live code in IdeOne.com.
Note that LocalDateTime lacks any concept of time zone or offset-from-UTC. So this does not represent a moment on the timeline. Apply a zone or offset if you know one was intended. Already covered many times on Stack Overflow; search for OffsetDateTime and ZonedDateTime.
As for database and SQLite, there are many other Questions and Answers already handling this. Your JDBC 4.2 driver may handle conversion of java.time types directly. If not, store as string using standard ISO 8601 format.
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.
You should work only with Date object instread of String. Format your date into string only when you whant to display it.
With a Date object you will be able to get the value in ms and do computation on it. You can also use Calendar to breakdown a date.
You should not work with String objects but Date instead. Only format date if and when you want to display it.
Date originalDate = new Date();
long diff = 60 * 1000; // milliseconds!
Date diffedDate = new Date(originalDate.getTime() - diff);
If you really want to do it the string way (which you should not), you can parse the date string like this:
String originalDateString = getDateTime(); // your current function
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date badlyDesignedOriginalDate = dateFormat.parse(originalDateString);
long diff = 60 * 1000; // milliseconds!
Date diffedDate = new Date(badlyDesignedOriginalDate.getTime() - diff);
But again, you should not do this.
You could use something like this:
long minute = 1000*60;
Date date1 = new Date(); //current date
Date date2 = new Date(date1.getTime() - minute); //new date, 1 minute older
//or another method
long minute = 1000*60;
Date date1 = new Date();
date1.setTime(date1.getTime() - minute);
Date works with milliseconds since January 1, 1970, 00:00:00 GMT, so you can substract it like normal numbers.
What is the most elegant way to get ISO 8601 formatted presentation of the current moment, UTC? It should look like: 2010-10-12T08:50Z.
Example:
String d = DateFormat.getDateTimeInstance(DateFormat.ISO_8601).format(date);
Use SimpleDateFormat to format any Date object you want:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
Using a new Date() as shown above will format the current time.
Java 8 Native
java.time makes it simple since Java 8. And thread safe.
ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT )
Result: 2015-04-14T11:07:36.639Z
You may be tempted to use lighter Temporal such as Instant or LocalDateTime,
but they lacks formatter support or time zone data.
Only ZonedDateTime works out of the box.
By tuning or chaining the options / operations of ZonedDateTime and DateTimeFormatter, you can easily control the timezone and precision, to a certain degree:
ZonedDateTime.now( ZoneId.of( "Europe/Paris" ) )
.truncatedTo( ChronoUnit.MINUTES )
.format( DateTimeFormatter.ISO_DATE_TIME )
Result: 2015-04-14T11:07:00+01:00[Europe/Paris]
Refined requirements, such as removing the seconds part, must still be served by custom formats or custom post process.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // 2015-04-14T11:07:00
.format( DateTimeFormatter.ISO_LOCAL_DATE ) // 2015-04-14
.format( DateTimeFormatter.ISO_LOCAL_TIME ) // 11:07:00
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm" ) ) // 2015-04-14 11:07
For Java 6 & 7, you may consider back-ports of java.time such as ThreeTen-Backport, which also has an Android port.
Both are lighter than Joda, and has learned from Joda's experience - esp. considering that java.time is designed by Joda's author.
For systems where the default Time Zone is not UTC:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
The SimpleDateFormat instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.
EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone does not accept a String (corrected by Paul)
As of Java 8 you can simply do:
Instant.now().toString();
From the java.time.Instant docs:
now
public static Instant now()
Obtains the current instant from the system clock.
This will query the system UTC clock to obtain the current instant.
toString
public String toString()
A string representation of this instant using ISO-8601 representation.
The format used is the same as DateTimeFormatter.ISO_INSTANT.
Java 8:
thisMoment = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX")
.withZone(ZoneOffset.UTC)
.format(Instant.now());
Pre Java 8:
thisMoment = String.format("%tFT%<tRZ",
Calendar.getInstance(TimeZone.getTimeZone("Z")));
From the docs:
'R' Time formatted for the 24-hour clock as "%tH:%tM"
'F' ISO 8601 complete date formatted as "%tY-%tm-%td".
use JodaTime
The ISO 8601 calendar system is the default implementation within Joda-Time
Here is the doc for JodaTime Formatter
Edit:
If you don't want to add or if you don't see value of adding above library you could just use in built SimpleDateFormat class to format the Date to required ISO format
as suggested by #Joachim Sauer
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());
DateFormatUtils from Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT
If you don't want to include Jodatime (as nice as it is)
javax.xml.bind.DatatypeConverter.printDateTime(
Calendar.getInstance(TimeZone.getTimeZone("UTC"))
);
which returns a string of:
2012-07-10T16:02:48.440Z
which is slightly different to the original request but is still ISO-8601.
ISO 8601 may contains seconds
see http://en.wikipedia.org/wiki/ISO_8601#Times
so the code should be
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
tl;dr
Some of the other Answers are correct in recommending java.time classes but go about using unnecessary lengths for your specific needs.
Instant.now() // Capture the current moment in UTC with a resolution as fines nanoseconds but usually in microseconds or milliseconds.
.truncatedTo( ChronoUnit.MINUTES ) // Lop off any seconds or fractional second, to get a value in whole minutes.
.toString() // Generate a String in standard ISO 8601 format where a `T` separates the year-month-day from the hour-minute-second, and the `Z` on the end for “Zulu” means UTC.
2018-01-23T12:34Z
Instant::toString
The jav.time.Instant class represents a moment in UTC, always in UTC.
Instant instant = Instant.now() ;
instant.toString(): 2018-01-23T12:34:56.123456Z
The Z on the end of your example string 2010-10-12T08:50Z is pronounced “Zulu” and means UTC.
Your desired format happens to comply with the ISO 8601 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern. Just call Instant::toString as seen above.
If you specifically want whole minutes without second or fractional second, then truncate. Specify a unit of time via ChronoUnit class.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
String output = instant.toString(); // Generate a `String` object in standard ISO 8601 format.
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.
Joda-Time
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. For Java 6 & 7, see the ThreeTen-Backport project, further adapted for Android in the ThreeTenABP project.
Using the Joda-Time library…
String output = new DateTime( DateTimeZone.UTC ).toString() ;
This is thread-safe. Joda-Time creates new immutable objects rather than changing existing objects.
If you truly intended to ask for a format without seconds, resolving to minutes, then use one of the many other built-in formatters in Joda-Time.
DateTime now = new DateTime( DateTimeZone.UTC ) ;
String output = ISODateTimeFormat.dateHourMinute.print( now ) ;
java.time
For Java 8 and later, Joda-Time continues to work. But the built-in java.time framework supplants Joda-Time. So migrate your code from Joda-Time to java.time as soon as is convenient.
See my other Answer for a modern solution.
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.
For Java version 7
You can follow Oracle documentation:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
X - is used for ISO 8601 time zone
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
System.out.println(nowAsISO);
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
//nowAsISO = "2013-05-31T00:00:00Z";
Date finalResult = df1.parse(nowAsISO);
System.out.println(finalResult);
I do believe the easiest way is to first go to instant and then to string like:
String d = new Date().toInstant().toString();
Which will result in:
2017-09-08T12:56:45.331Z
You could use Java's SimpleDateFormat with the following pattern yyyy-MM-dd'T'HH:mm:ssXXX for ISO 8601.
Sample Code: (lists out for all the available time zones)
for (String timeZone : TimeZone.getAvailableIDs())
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
String formatted = dateFormat.format(new Date());
System.out.print(formatted);
if (formatted.endsWith("Z"))
{
// These time zone's have offset of '0' from GMT.
System.out.print("\t(" + timeZone + ")");
}
System.out.println();
}
You could use:
TimeZone.getDefault()
for the default vm timezone. More here
You might notice the date time for few time zones that end with 'Z'. These time zones have offset of '0' from GMT.
More info can be found here.
private static String getCurrentDateIso()
{
// Returns the current date with the same format as Javascript's new Date().toJSON(), ISO 8601
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.format(new Date());
}
Here's a whole class optimized so that invoking "now()" doesn't do anything more that it has to do.
public class Iso8601Util
{
private static TimeZone tz = TimeZone.getTimeZone("UTC");
private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
static
{
df.setTimeZone(tz);
}
public static String now()
{
return df.format(new Date());
}
}
DateTimeFormatter.ISO_DATE_TIME
.withZone(ZoneOffset.UTC)
.format(yourDateObject.toInstant())
Still, joda-time does only support the extended format:
"2015-12-09T00:22:42.930Z"
not the basic:
"20151209T002242.930Z"
...we might be better off testing a list of formats with java SimpleDateFormat.
I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.
private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";
public static Calendar isoToCalendar(final String inputDate) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
Date date = dateFormat.parse(inputDate);
calendar.setTime(date);
} catch (ParseException e) {
Log.e("TAG",e.getMessage());
}
return calendar;
}
REMEMBER:
The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.
If you care about performance, I created a library which outperforms standard Java parser and formatter in manipulating with ISO8601-formatted dates. DatetimeProcessor implementations are thread-safe and can be cached in a concurrent map or static fields.
<dependency>
<groupId>com.axibase</groupId>
<artifactId>date-processor</artifactId>
<version>1.0.3</version>
</dependency>
import com.axibase.date.DatetimeProcessor;
import com.axibase.date.PatternResolver;
import org.junit.Before;
import org.junit.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class DateFormatTest {
private Clock clock;
#Before
public void prepare() {
clock = Clock.fixed(Instant.ofEpochMilli(1571285405300L), ZoneId.of("Europe/Berlin"));
}
#Test
public void testIsoMillis(){
final DatetimeProcessor formatter = PatternResolver.createNewFormatter("iso");
assertThat(formatter.print(clock.millis(), ZoneOffset.UTC), is("2019-10-17T04:10:05.300Z"));
}
#Test
public void testIsoMillisLocalZone(){
final DatetimeProcessor formatter = PatternResolver.createNewFormatter("iso");
assertThat(formatter.print(clock.millis(), clock.getZone()), is("2019-10-17T06:10:05.300+02:00"));
}
#Test
public void testIsoMinutes(){
final DatetimeProcessor formatter = PatternResolver.createNewFormatter("yyyy-MM-ddTHH:mmXXX");
assertThat(formatter.print(clock.millis(), ZoneOffset.UTC), is("2019-10-17T04:10Z"));
}
}
They should have added some kind of simple way to go from Date to Instant and also a method called toISO8601, which is what a lot of people are looking for.
As a complement to other answers, from a java.util.Date to ISO 8601 format:
Instant.ofEpochMilli(date.getTime()).toString();
It is not really visible when using auto-completion but:
java.time.Instant.toString():
A string representation of this instant using ISO-8601
For those using Joda Time, here's a one-liner in the format yyyy-MM-dd'T'HH:mm:ss'Z'
DateTime(timeInMillis, DateTimeZone.UTC).toString(ISODateTimeFormat.dateTimeNoMillis())
Try This,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
String date=sdf.format (new Date() );
Its For ISO 8601 format
Is there a straightforward way of converting a Java SQL Date from format yyyy-MM-dd to dd MMMM yyyy format?
I could convert the date to a string and then manipulate it but I'd rather leave it as a Java SQL Date. at the time I need to do this, the data has already been read from the MySQL database so I cant do the change there.
Object such as java.sql.Date and java.util.Date (of which java.sql.Date is a subclass) don't have a format of themselves. You use a java.text.DateFormat object to display these objects in a specific format, and it's the DateFormat (not the Date itself) that determines the format.
For example:
Date date = ...; // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);
Note: When you print a Date object without using a DateFormat object, like this:
Date date = ...;
System.out.println(date);
then it will be formatted using some default format. That default format is however not a property of the Date object that you can change.
If it is for presentation you can use SimpleDateFormat straight away:
package org.experiment;
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Dates {
private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");
public static void main(String[] args){
Date oneDate = new Date(new java.util.Date().getTime());
System.out.println(df.format(oneDate));
}
}
It's not clear what you mean by a "Java SQL Date". If you mean as in java.sql.Date, then it doesn't really have a string format... it's just a number. To format it in a particular way, use something like java.text.SimpleDateFormat.
Alternatively, convert it to a Joda Time DateTime; Joda Time is a much better date and time API than the built-in one. For example, SimpleDateFormat isn't thread-safe.
(Note that a java.sql.Date has more precision than a normal java.util.Date, but it looks like you don't need that here.)
tl;dr
myJavaSqlDate.toLocalDate()
.format(
DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG )
.withLocale ( Locale.UK )
)
11 May 2017
Do not conflate date-time values with their textual representation
As others said, a date-time object has no format. Only strings generated from the object or parsed by the object have a format. But such strings are always separate and distinct from the date-time object.
Use objects, not strings
Avoid using strings to communicate date-time values to/from your database. For date-time values, use date-time classes to instantiate date-time objects.
The very purpose of JDBC is to mediate the differences in types between your database and Java.
Using java.time
The other Answers are outdated as they use the troublesome old legacy date-time classes or the venerable Joda-Time library. Both have been supplanted by the java.time classes.
If you have a java.sql.Date object in hand, convert to java.time.LocalDate by calling the new method toLocalDate added to the old class.
LocalDate ld = myJavaSqlDate.toLocalDate() ;
For JDBC drivers that comply with JDBC 4.2 and later, you can work directly with java.time types.
You seem to be interested in the date-only values. So use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
PreparedStatement::setObjectmyPStmt.setObject( … , myLocalDate )
ResultSet::getObjectmyResultSet.getObject( … , LocalDate.class )
To generate a string in your desired format, you could specify a custom formatting pattern. But I suggest 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…
LocalDate ld = LocalDate.now ( ZoneId.of ( "America/Montreal" ) ); // Today's date at this moment in that zone.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.UK );
String output = ld.format ( f );
output: 11 May 2017
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.