I was looking for the simplest way to convert a date an time from GMT to my local time. Of course, having the proper DST dates considered and as standard as possible.
The most straight forward code I could come up with was:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String inpt = "2011-23-03 16:40:44";
Date inptdate = null;
try {
inptdate = sdf.parse(inpt);
} catch (ParseException e) {e.printStackTrace();}
Calendar tgmt = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
tgmt.setTime(inptdate);
Calendar tmad = new GregorianCalendar(TimeZone.getTimeZone("Europe/Madrid"));
tmad.setTime(inptdate);
System.out.println("GMT:\t\t" + sdf.format(tgmt.getTime()));
System.out.println("Europe/Madrid:\t" + sdf.format(tmad.getTime()));
But I think I didn't get the right concept for what getTime will return.
The catch here is that the DateFormat class has a timezone. Try this example instead:
SimpleDateFormat sdfgmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfmad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfmad.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
String inpt = "2011-23-03 16:40:44";
Date inptdate = null;
try {
inptdate = sdfgmt.parse(inpt);
} catch (ParseException e) {e.printStackTrace();}
System.out.println("GMT:\t\t" + sdfgmt.format(inptdate));
System.out.println("Europe/Madrid:\t" + sdfmad.format(inptdate));
Here is the 2017 answer.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String inpt = "2011-03-23 16:40:44";
ZonedDateTime madridTime = LocalDateTime.parse(inpt, dtf)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.of("Europe/Madrid"));
System.out.println("GMT:\t\t" + inpt);
System.out.println("Europe/Madrid:\t" + madridTime.format(dtf));
Please enjoy how much more naturally this code expresses the intent.
The code prints
GMT: 2011-03-23 16:40:44
Europe/Madrid: 2011-03-23 17:40:44
(with tab size of 8 it aligns nicely, but StackOverflow seems to apply a tab size of 4).
I swapped 23 and 03 in your input string, I believe you intended this. BTW, it wasn’t me catching your mistake, it was LocalDateTime.parse() throwing an exception because there is no 23rd month. Also in this respect the modern classes are more helpful than the outdated ones.
Joda-Time? Basil Bourque’s answer mentions and recommends both java.time, which I am using, and Joda-Time. While Joda-Time is already a sizeable improvement over the outdated classes used in the question (SimpleDateFormat, Calendar, GregorianCalendar), it is by now in maintenance mode; no greater further development is expected. java.time is hugely inspired by Joda-Time. For new code, I see no reason why you shouldn’t prefer java.time.
For the input, you can simply add the Timezone to the String (note the 'z' in the format):
new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss z").parse ("2011-23-03 16:40:44 GMT");
The simplest way is to use a decent date-time library rather than the notoriously troublesome java.util.Date and .Calendar classes. Instead use either Joda-Time or the java.time package found in Java 8.
Joda-Time
String input = input.replace( " ", "T" ).concat( "Z" ) ; // proper ISO 8601 format for a date-time in UTC.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Madrid" );
DateTime dateTime = new DateTime( input, timeZone );
String output = dateTime.toString();
You need to set the TimeZone on the SimpleDateFormat, using DateFormat.setTimeZone().
Related
I will be direct with my question. I am wondering why I can't parse a fromat MMM-dd-yyyy into yyyy-MM-dd (java.sql.Date format)? Any suggestion on how I am going to convert a String into a format of (yyyy-MM-dd)?
Here is the code:
public DeadlineAction(String deadline){
putValue(NAME, deadline);
deadLine = deadline;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd");
try {
finalDate = (Date) formatter.parse(deadLine);
}catch(ParseException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
Thank you
Basically, you can't parse a String in the format of MMM-dd-yyyy using the format of yyyy MM dd, it just doesn't make sense, you need one formatter to parse the value and another to format itm for example
SimpleDateFormat to = new SimpleDateFormat("yyyy MM dd");
SimpleDateFormat from = new SimpleDateFormat("MMM-dd-yyyy");
Date date = from.parse(deadLine);
String result = to.format(date)
The question that needs to be asked is, why you would bother. If your intention is to put this value into the database, you should be creating an instance of java.sql.Date (from the java.util.Date) and using PreparedStatement#setDate to apply it to your query, then letting the JDBC driver deal with it
The answer by MadProgrammer is correct. You must define a formatting pattern to fit the format of your input data string.
You could avoid the problem in the first place by using the java.time framework.
java.time
The java.time framework is built into Java 8 and later (also back-ported to Java 6 & 7 and to Android). These classes supplant the old troublesome legacy date-time classes (java.util.Date/.Calendar).
ISO 8601
Your input strings are apparent is standard ISO 8601 format, YYYY-MM-DD such as 2016-01-23.
The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern.
Parsing string
For a date-only value without time-of-day and without time zone, use LocalDate class.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Generating string
To generate a string representing that LocalDate object’s value, just call toString to get a string in ISO 8601 format.
String output = localDate.toString(); // 2016-01-23
For other formats, use the java.time.format package. Usually best to let java.time automatically localize to the user’s human language and cultural norms defined by a Locale.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );
Locale locale = Locale.CANADA_FRENCH;
formatter = formatter.withLocale( locale );
String output = localDate.format( formatter );
Or you can specify your own particular pattern. Note that you should still specify a Locale to determine aspects such as the name-of-month or name-of-day. Here is a demo of the pattern that seems to be asked in the Question (not sure as Question is unclear).
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM-dd-yyyy" );
Locale locale = Locale.US;
formatter = formatter.withLocale( locale );
String output = localDate.format( formatter );
Try something like:
try {
final String deadLine = "Oct-12-2006";
SimpleDateFormat formatter = new SimpleDateFormat("MMM-dd-yyyy");//define formatter for yout date time
Date finalDate = formatter.parse(deadLine);//parse your string as Date
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");// define your desired format
System.out.println(formatter2.format(finalDate));//format the string to your desired date format
} catch (Exception e) {
//handle
}
Your example is not unparseable. I removed the dashes from MMM-dd-yyyy to MMM dd yyyy. You can put them back if needed. I also removed the any extra code to make the solution clear.
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public DeadlineAction(String deadline){
//if deadline has format similar to "December 19 2011"
try {
finalDate = new java.sql.Date(
((java.util.Date) new SimpleDateFormat("MMM dd yyyy").parse(deadline)).getTime());
}catch(ParseException e) {
//Your exception code
e.printStackTrace();
}
}
This works for almost every conversion to sqlDate. Just change SimpleDateFormat("MMM dd yyyy") to what you need it to be.
Example: new SimpleDateFormat("MMM-yyyy-dd").parse("NOVEMBER-2012-30")
This question already has answers here:
Date and time conversion to some other Timezone in java
(11 answers)
Closed 8 years ago.
I have a string with gmt date value and -06:00 at end. What is best way to convert this to CST? I looked at other questions but none of them have -06:00 at end to answer my question.
This is what I tried and it errors out as java.text.ParseException: Unparseable date: "2015-02-19T11:50:09.5953377-06:00"
private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSSSSS'Z'");
private DateFormat gmtFormat = new SimpleDateFormat();
private TimeZone cstTime = TimeZone.getTimeZone("CST");
gmtFormat.setTimeZone(cstTime);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
System.out.println("cst start date is " + gmtFormat.format("2015-02-19T11:50:09.5953377-06:00"));
} catch (ParseException e) {
e.printStackTrace();
}
I've run into similar problems before, where I was actually getting dates in 3 different iso formats like that, and was pretty frustrated with it... This isn't pretty, but it may help point you in the right direction...
The 3 formats I was getting the info in:
private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String ISO_FORMAT2 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static final String ISO_FORMAT3 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
Actually attempting to parse them (without having to figure out the correct type beforehand, returning a new Date Object in the event all 3 failed so shit doesn't crash because of a damn date formatting exception):
public static Date parseIso(String date){
SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e) {
Log.g(TAG, "Failed 1st date parse with " + ISO_FORMAT + " for " + date);
sdf = new SimpleDateFormat(ISO_FORMAT2, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e2) {
Log.g(TAG, "Failed 2nd date parse with " + ISO_FORMAT2 + " for " + date);
sdf = new SimpleDateFormat(ISO_FORMAT3, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return sdf.parse(date);
}
catch (ParseException e3) {
Log.g(TAG, "Failed 3rd date parse with " + ISO_FORMAT3 + " for " + date);
}
}
}
return new Date();
}
And then for actually converting that date to a localized date:
public static String format(long mils, String format){
return format(getInstance(mils), format);
}
public static String format(Calendar calendar, String format){
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(new Date(calendar.getTime().getTime() + TimeZone.getDefault().getOffset(new Date().getTime())));
}
public static Calendar getInstance(long timeInMils){
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(timeInMils);
return cal;
}
So now you can basically call
CalendarHelper.format(myDateObject.getTime(), "MMM dd, yyyy");
and it will return the localized, formatted date from the original UTC date you received.
Again, not pretty, but I hope this can point you in the right direction for converting between the UTC and client's time zone. Best of luck~
PS. I think ISO_FORMAT_3 is the one that will actually help you. I guess I probably could have started with that information, but I'm not a bright man.
ISO 8601
You seem to misunderstand the meaning of the input string, 2015-02-19T11:50:09.5953377-06:00. You do not have a "gmt date value".
That format appears to be the standard ISO 8601 format.
The T in the middle separates the date portion from the time-of-day portion.
The -06:00 at the end is an offset from UTC. It means "the date-time value shown here is six hours behind UTC".
CST
So, if by CST you mean Central Time Zone (some of the middle parts of the Americas continents), then you need have no conversion to perform. That string with the time 11:50 means "almost noon in Illinois, Arkansas, and Louisiana". If you add 6 hours to 11:50, you would learn the UTC (GMT) date-time at that same moment: 17:50 on same date.
Avoid 3-4 Letter Codes
By the way, avoid using three or four letter time zone codes such as "CST". Those codes are not standardized nor unique. Many duplicates exist. For example, take CST:
Central Standard Time (Americas)
China Standard Time
Central Standard Time (Australia)
Central Summer Time (Australia)
Cuba Standard Time
Instead use proper time zones. Most of these are continent plus a slash plus a city/region. Examples: America/Regina, America/Monterrey, and America/Indiana/Knox.
Joda-Time | java.time
The java.util.Date/.Calendar classes are notoriously troublesome. Avoid them.
Use either the Joda-Time library or the new java.time package built into Java 8. The java.time package is inspired by Joda-Time but is re-architected. Each has its own strengths and weaknesses.
Both Joda-Time and java.time use ISO 8601 formats as their defaults for both parsing and generating string representations of date-time values.
As this Question is really a duplicate with hundreds of such Questions and Answers already posted, I'll give just one quick example.
String input = "2015-02-19T11:50:09.5953377-06:00";
DateTimeZone zoneAmerica_Regina = DateTimeZone.forID( "America/Regina" );
DateTime dateTimeAmericaRegina = new DateTime( input, zoneAmerica_Regina );
DateTime dateTimeLosAngeles = dateTimeAmericaRegina.withZone( DateTimeZone.forID( "America/Los_Angeles" ) );
DateTime dateTimeUtc = dateTimeAmericaRegina.withZone( DateTimeZone.UTC );
Fractional Seconds
Your input string has a very small fraction of a second. Joda-Time (like java.util.Date) handles only millisecond resolution — three digits after the decimal point. The java.item package handles nanosecond resolution. Some systems use microsecond resolution, such as database like Postgres. And some systems follow the old Unix convention of whole seconds.
I'm getting these times from Facebook events. E.g: start_time and it's a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
I tried to do it with this:
SimpleDateFormat formatter = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
Date formatted = null;
try {
formatted = formatter.parse(p.getStart_time());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedString = formatted.toString();
txtStart_time.setText(""+formattedString);
p.getStart_time() is a String that gives me the date like I said before.
If I do this method, I get an error:
Unparseable date.
Does anybody know a work around?
You need two formats: one to parse the date and one to format it
String startTime = "2013-12-21T18:30:00+0100";
SimpleDateFormat incomingFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = incomingFormat.parse(startTime);
SimpleDateFormat outgoingFormat = new SimpleDateFormat(" EEEE, dd MMMM yyyy", java.util.Locale.getDefault());
System.out.println(outgoingFormat.format(date));
prints
Saturday, 21 December 2013
I'm getting these times from Facebook events. E.g: start_time and it's
a string like this:
2013-12-21T18:30:00+0100
Now I just want the time, like:
18.30
Solution using java.time, the modern date-time API:
OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime()
Description: Your date-time string has a timezone offset of +01:00 hours. java.time API provides you with OffsetDateTime to contain the information of date-time units along with the timezone offset. Using the applicable DateTimeFormatter, parse the string into an OffsetDateTime and then get the LocalTime part of this date-time using OffsetDateTime#toLocalTime.
Demo using java.time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
System.out.println(OffsetDateTime.parse(
"2013-12-21T18:30:00+0100",
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ")
).toLocalTime());
}
}
Output:
18:30
ONLINE DEMO
Note: You can use y instead of u here but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
A note about the legacy API:
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2013. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Use something like yyyy-MM-dd'T'HH:mm:ssZ as parsing format instead of EEEE, dd MMMM yyyy.
Substring
If all you want is literally the time component lifted from that string, call the substring method on the String class…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String dateTimeStringFromFacebook = "2013-12-21T18:30:00+0100";
// Extract a substring.
String timeSubstring = dateTimeStringFromFacebook.substring( 11, 19 );
DateTime Object
If you want the time converted to a particular time zone, convert the string to a date-time object. Use a formatter to express just the time component.
Here is some example code using the Joda-Time 2.3 library. Avoid the notoriously bad java.util.Date/Calendar classes. Use either Joda-Time or the new java.time.* JSR 310 classes bundled with Java 8.
// From String to DateTime object.
DateTime dateTime = new DateTime( dateTimeStringFromFacebook, DateTimeZone.UTC );
// From DateTime object to String
// Extract just the hours, minutes, seconds.
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
String timeFragment_Paris = formatter.withZone( DateTimeZone.forID( "Europe/Paris" ) ).print( dateTime );
String timeFragment_Kolkata = formatter.withZone( DateTimeZone.forID( "Asia/Kolkata" ) ).print( dateTime ); // Formerly known as Calcutta, India.
Dump to console…
System.out.println( "dateTimeStringFromFacebook: " + dateTimeStringFromFacebook );
System.out.println( "timeSubstring: " + timeSubstring );
System.out.println( "dateTime: " + dateTime );
System.out.println( "timeFragment_Paris: " + timeFragment_Paris );
System.out.println( "timeFragment_Kolkata: " + timeFragment_Kolkata + " (Note the 00:30 difference due to +05:30 offset)");
When run…
dateTimeStringFromFacebook: 2013-12-21T18:30:00+0100
timeSubstring: 18:30:00
dateTime: 2013-12-21T17:30:00.000Z
timeFragment_Paris: 18:30:00
timeFragment_Kolkata: 23:00:00 (Note the 00:30 difference due to +05:30 offset)
Think Time Zone
Your question fails to address the question of time zone. Make a habit of always thinking about time zone whenever working with date-time values. If you mean the same time zone, say so explicitly. If you mean the default time zone of the Java environment, say so. If you mean UTC… well, you get the idea.
// Im new to java programming
I have a String object that represents a date/time in this format : "2013-06-09 14:20:00" (yyyy-MM-dd HH:mm:ss)
I want to convert it to a Date object so i can perform calculations on it but im confused on how to do this.
I tried :
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(date);
//Prints Mon Dec 31 00:00:00 GMT 2012
Any help appreciated
Ok so I have now updated my code to as follows i'm getting the correct date/time now when I print the date but is this the correct implementation :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string);
System.out.println(dateFormat.format(date));
//prints 2013-06-09 14:20:00
Thx to everyone that's answered/commented thus far
The format is wrong. Use this instead:
"yyyy-dd-MM HH:mm:ss"
Indeed your last program version is ok, except you don't need to declare the SimpleDateFormat twice. Simply:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = dateFormat.parse(string);
System.out.println(dateFormat.format(date));
String string = "2013-06-09 14:20:00";
and the DATE object format is "yyyy-dd-MM HH:mm:ss"
You can get Date,Day,month and many more by using Date object which is present in
java.util.Date package , like as follows.
Date d = new Date(string);
This will call constructor of Date object for which you are passing 'string' variable which contains date.
d.getDay(); // retrieve day on that particular day
d.getDate(); // retrieve Date
and many more are avaiable like this.
Using java.util.Date
The answer by zzKozak is correct. Well, almost correct. The example code omits required exception handling. Like this…
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = "2013-06-09 14:20:00";
Date date = null;
try {
date = dateFormat.parse(string);
} catch ( ParseException e ) {
e.printStackTrace();
}
System.out.println("date: " + dateFormat.format(date));
Don't Use java.util.Date!
Avoid using java.util.Date & Calendar classes bundled with Java. They are notoriously bad in both design and implementation.
Instead use a competent date-time library. In Java that means either:
The third-party open-source Joda-Time
In the forthcoming Java 8, the new java.time.* classes defined by JSR 310 and inspired by Joda-Time.
Time Zone
Your question and code fail to address the issue of time zones. If you ignore time zones, you'll get defaults. That may cause unexpected behaviors when deployed in production. Better practice is to always specify a time zone.
Formatter
If you replace a space with a 'T' per the standard ISO 8601 format, then you can conveniently feed that string directly to a constructor of a Joda-Time DateTime instance.
If you must use that string as-is, then define a formatter to specify that format. You can find many examples of that here on StackOverflow.com.
Example Code
Here is some example code using Joda-Time 2.3, running in Java 7.
I arbitrarily chose a time zone of Montréal.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( "2013-06-09T14:20:00", timeZone ); // Or pass DateTimeZone.UTC as time zone for UTC/GMT.
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2013-06-09T14:20:00.000-04:00
I want to convert a java.util.Date object to a String in Java.
The format is 2010-05-30 22:15:52
Convert a Date to a String using DateFormat#format method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
tl;dr
myUtilDate.toInstant() // Convert `java.util.Date` to `Instant`.
.atOffset( ZoneOffset.UTC ) // Transform `Instant` to `OffsetDateTime`.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String.
.replace( "T" , " " ) // Put a SPACE in the middle.
2014-11-14 14:05:09
java.time
The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.
First convert your java.util.Date to 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).
Conversions to/from java.time are performed by new methods added to the old classes.
Instant instant = myUtilDate.toInstant();
Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.
String output = instant.toString();
2014-11-14T14:05:09Z
For other formats, you need to transform your Instant into the more flexible OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
See that code run live at IdeOne.com.
To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.
Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.
To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]
To generate a formatted String, do the same as above but replace odt with zdt.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
Apply that formatter by passing the instance.
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old 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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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.
Altenative one-liners in plain-old java:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.
Slightly more repetitive but needs just one statement.
This may be handy in some cases.
Why don't you use Joda (org.joda.time.DateTime)?
It's basically a one-liner.
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
It looks like you are looking for SimpleDateFormat.
Format: yyyy-MM-dd kk:mm:ss
In single shot ;)
To get the Date
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
To get the Time
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
To get the date and time
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Happy coding :)
public static String formateDate(String dateString) {
Date date;
String formattedDate = "";
try {
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formattedDate;
}
If you only need the time from the date, you can just use the feature of String.
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
This will automatically cut the time part of the String and save it inside the timeString.
Here are examples of using new Java 8 Time API to format legacy java.util.Date:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
.withZone(ZoneOffset.UTC);
String utcFormatted = formatter.format(date.toInstant());
ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
// gives the same as above
ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
// 2011-12-03T10:15:30+01:00[Europe/Paris]
String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).
List of predefined fomatters and pattern notation reference.
Credits:
How to parse/format dates with LocalDateTime? (Java 8)
Java8 java.util.Date conversion to java.time.ZonedDateTime
Format Instant to String
What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The easiest way to use it is as following:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh
- HH refers to 24h time format
- hh refers to 12h time format
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
From Convert Date to String in Java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not
logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());