This question already has answers here:
How to combine date and time into a single object?
(3 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Closed 4 years ago.
I have a small gui which have a datepicker and a textbox where I enter a time (HH:mm).
I want to create a method whish takes the Date from the datepicker and adds the time (HH:mm) to the datepicker-date and then returns the Date so I can save it in a database.
I want to have the final date in this format "yyyy-MM-dd HH:mm"
This is what I have tried:
public Date getCalibrationDate(){
String time = getTime();
int hours = Integer.parseInt(time.substring(0,2));
int minutes = Integer.parseInt(time.substring(2,4));
Date date = java.sql.Date.valueOf(kalibreringsdatum.getValue());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE,minutes);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateAsString = sdf.format(calendar.getTime());
Date dateTime = null;
try {
dateTime = sdf.parse(dateAsString);
} catch (ParseException e) {
System.out.println("Could not parse date");
e.printStackTrace();
}
return dateTime;
}
But it returns the date in this way: Tue Dec 11 11:22:00 CET 2018.
What am I doing wrong and how can I simplify the method?
tl;dr
For database column of type TIMESTAMP WITHOUT TIME ZONE.
myPreparedStatement // As of JDBC 4.2, send/receive java.time objects to/from your database.
.setObject( // Call `PreparedStatement::setObject` and `ResultSet::getObject` for java.time objects.
… , // Fill-in to indicate which placeholder in SQL statement.
LocalDateTime.of( // Represent a date with time-of-day, but lacking in zone/offset so NOT a moment, NOT a point on the timeline.
LocalDate.parse( "2018-01-23" ) , // Parse the date-only value.
LocalTime.parse( "21:54" ) // Parse the time-of-day.
) // Returns a `LocalDateTime` object.
)
For database column of type TIMESTAMP WITH TIME ZONE.
myPreparedStatement // As of JDBC 4.2, send/receive java.time objects to/from your database.
.setObject( // Call `PreparedStatement::setObject` and `ResultSet::getObject` for java.time objects.
… , // Fill-in to indicate which placeholder in SQL statement.
LocalDateTime.of( // Represent a date with time-of-day, but lacking in zone/offset so NOT a moment, NOT a point on the timeline.
LocalDate.parse( "2018-01-23" ) , // Parse the date-only value.
LocalTime.parse( "21:54" ) // Parse the time-of-day.
) // Returns a `LocalDateTime` object.
.atZone( // Assign a time zone to make a moment.
ZoneId.of( "Pacific/Auckland" ) // Real time zones have a proper name in `Continent/Region` format. Never use 2-4 letter pseudo-zones such as `PDT`, `IST`, `CST`, etc.
) // Returns a `ZonedDateTime` object.
.toOffsetDateTime() // Strip out the time zone, leaving only a mere offset-from-UTC (a number of hours-minutes-seconds). Returns a `OffsetDateTime` object.
.withOffsetSameInstant( // Adjust the offset-from-UTC to UTC itself (an offset of zero). Same moment, different wall-clock time.
ZoneOffset.UTC
) // Returns another `OffsetDateTime` object.
)
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible old legacy classes (Calendar, Date, SimpleDateFormat, etc.).
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
The common SQL format for a date-only value in text is YYYY-MM-DD. This is also the format defined by the ISO 8601 standard. The java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2018-01-23" ) ;
Similar for a string in format of HH:MM for hours and minutes of a time-of-day.
LocalTime lt = LocalTime.parse( "21:54" ) ;
Combine the date with the time.
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
ldt.toString(): 2018-01-23T21:54
Be aware that a LocalDateTime, purposely lacking any concept of time zone or offset-from-UTC, is not a moment, is not a point on the timeline. As such, it is only appropriate to save to a database in a column of a data type akin to the SQL-standard TIMESTAMP WITHOUT TIME ZONE.
JDBC 4.2
As of JDBC 4.2, we can directly exchange java.time objects with the database via setObject & getObject.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
ZonedDateTime
If you want to work with moments, actual points on the timeline, use the appropriate Java classes (Instant, OffsetDateTime, ZonedDateTime).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
OffsetDateTime
Now we have a moment at hand. Usually best to focus on UTC when moving dates around such as transferring to a database.
OffsetDateTime odtUtc = zdt.toOffsetDateTime().withOffset( ZoneOffset.UTC ) ;
Send to database.
myPreparedStatement.setObject( … , odtUtc ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
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.
You can use SimpleDateFormat to get what you want:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateAndTime {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
System.out.println(sdf.format(new Date()))
}
}
Related
I need to convert a Date which is in CST to required time zone. I will get Date as String like "11/5/2018 12:54:20" which is in CST time zone. I have to convert this to a time zone which is passed as a parameter. suppose lets take it as "GMT+0530".
The result for the above date ideally "Nov 06 2018 00:24:20"
I have tried the below code which returned the passed date(11/05/2018 12:54:20) as same instead of(Nov 06 2018 00:24:20) . I have executed this on a system which has IST time zone.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT-0600"));
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
System.out.println(sdf2.format(sdf.parse("11/5/2018 12:54:20").getTime()));
Edit:
Answer:
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "11/5/2018 12:54:20" , f ) ;
ZoneId z = ZoneId.of( "GMT-0600" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
System.out.println(zdt);
ZoneId zKolkata = ZoneId.of( "GMT+0530" ) ;
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata ) ;
System.out.println(zdtKolkata);
tl;dr
LocalDateTime // Represent a date and a time-of-day, without offset nor zone. So *not* a moment, *not* a point on the timeline.
.parse(
"11/5/2018 12:54:20" ,
DateTimeFormatter.ofPattern( "d/M/uuuu HH:mm:ss" ) // Define a formatting pattern to match your input string.
) // Returns a `LocalDateTime`.
.atZone( // Assign a time zone, to give meaning to the `LocalDateTime` object, making it a `ZonedDateTime` object.
ZoneId.of( "America/New_York" ) // Define a time zone properly with `Continent/Region` naming, never 2-4 letter pseudo-zones such as CST or IST.
) // Returns a `ZonedDateTime` object.
.withZoneSameInstant( // Adjust from New York time to Kolkata time. Some moment, different wall-clock time.
ZoneId.of( "Asia/Kolkata" )
) // Returns another `ZonedDateTime` object rather than altering (“mutating”) the original, per Immutable Objects pattern.
.toString() // Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
2018-05-11T22:24:20+05:30[Asia/Kolkata]
java.time
You are using terrible old classes, now supplanted by java.time classes.
Parse your input string as a LocalDateTime because it lacks any indication of offset-from-UTC or time zone.
Define a formatting pattern to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "11/5/2018 12:54:20" , f ) ;
ldt.toString(): 2018-05-11T12:54:20
You say this was intended for CST. Did you mean China Standard Time? Or Central Standard Time in North America?
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as CST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
I will assume you meant something like New York time.
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2018-05-11T12:54:20-04:00[America/New_York]
And apparently you want to see this same moment through the lens of the wall-clock time used by the people of a different region, a different time zone. By IST did you mean Irish Standard Time? Or India Standard Time? Again, use real time zones not these 2-4 character pseudo-zones.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata ) ;
zdtKolkata.toString(): 2018-05-11T22:24:20+05:30[Asia/Kolkata]
To see the same moment in UTC, extract a Instant.
Instant instant = zdtKolkata.toInstant() ;
instant.toString(): 2018-05-11T16:54:20Z
All three of these ( zdt, zdtKolkata, instant ) all represent the same moment, the same point on the timeline.
In contrast, the ldt as a LocalDateTime object does not represent a moment, is not a point on the timeline. It held no real meaning until you assigned it a time zone to give it a context. Until assigning that zone, we do not know if meant noon hour in Australia or in Africa, or in America. It could have meant any of about 26-27 hours, the range of time zones around the globe.
ISO 8601
Rather than inventing your own formats for exchanging date-time values as text, use the standard ISO 8601 formats.
The java.time classes conveniently use ISO 8601 formats by default when generating/parsing strings.
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.
You are setting the timezone of sdf twice and not setting timezone of sdf2 and thus getting incorrect results. Also, you don't need to call getTime() when passing object to DateFormat::format().
Here is a fixed version of your code:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
TimeZone cstTimeZone = TimeZone.getTimeZone("CST");
sdf.setTimeZone(cstTimeZone);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
System.out.println(sdf2.format(sdf.parse("11/5/2018 12:54:20")));
Note that the classes you are using are quite old and since version 8, Java provides new Date and Time APIs.
This question already has answers here:
Adding n hours to a date in Java?
(16 answers)
Closed 4 years ago.
How do i add hours to a date object. Below is my code:
String dateStart = timeStamp;
String dateStop = valueCon;
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(dateStart);
d2 = format.parse(datestop);
I want to add 4 hours to d2 date object. How do i achieve it?
I tried to use :
Date modd1= new Date(d2+TimeUnit.MINUTES.toHours(240));
But it accepts only long object for adding. Thus failed.
Please support to solve this.Thanks in advance.
like others, i'd recommend using java.time if that's an option. the APIs are more consistent, and do a better job of catering to these types of operations.
however, to answer your question as-is... one option is to adjust the millisecond form of the Date instance by using get/setTime() as follows:
#Test
public void adjustTime() {
final Date date = new Date();
System.out.println("## Before adding four hours: " + date);
date.setTime(date.getTime() + TimeUnit.HOURS.toMillis(4));
System.out.println("## After adding four hours: " + date);
}
hope that helps!
If you are using java.time it can be more helpful :
LocalDateTime dateStart = LocalDateTime.now();
LocalDateTime dateStop = dateStart.plusHours(4);
To format the date you can use :
String d1 = dateStart.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
String d2 = dateStop.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
Well there are several ways to do
Using Calendar class
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(anyDateObject); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 4); // adds four hour
Date date = cal.getTime(); // returns new date object
If you are using ApacheCOmmon Lang
Date newDate = DateUtils.addHours(oldDate, 3);
If you are using Joda-time
DateTime dt = new DateTime();
DateTime added = dt.plusHours(4);
and if you are using Java 8 best would be LocalDateTime
LocalDateTime startDate = LocalDateTime.now();
LocalDateTime stopdate = startDate.plusHours(4);
tl;dr
Never use Date or SimpleDateFormat classes.
Use only modern java.time classes.
Example code:
LocalDateTime.parse( // Parsing input string to an object without concept of zone or offset.
"18/01/23 12:34:56" , // Input lacking indicator of zone/offset.
DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) // Define formatting pattern matching your input.
)
.plusHours( 4 ) // Add four hours. Generating a new `LocalDateTime` object, per immutable objects pattern.
.toString() // Generate a String in standard ISO 8601 format.
2018-01-23T16:34:56
java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Never use Date, Calendar, SimpleDateFormat.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) ;
Unzoned
Apparently your input lacks an indicator of time zone or offset-from-UTC. So parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( "18/01/23 12:34:56" ) ;
ldt.toString(): 2018-01-23T12:34:56
A LocalDateTime has no concept of time zone or offset-from-UTC. So it does not represent an actual moment, and is not a point on the timeline. A LocalDateTime is only a rough idea about potential moments along a range of about 26-27 hours.
Zoned
If you know for certain the input data was intended to represent a moment in a particular zone, apply a ZoneId to produce a ZonedDateTime. A ZonedDateTime does represent an actual moment, a point on the timeline.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Determining an actual moment.
zdt.toString(): 2018-01-23T12:34:56+01:00[Africa/Tunis]
To see the same moment in UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
Math
Represent a span of time unattached to the timeline as a Duration object.
Duration d = Duration.ofHours( 4 ) ; // Four hours, as an object.
Add to your LocalDateTime, if not using time zones.
LocalDateTime ldtLater = ldt.plus( d ) ;
If using zoned values, add to your ZonedDateTime.
ZonedDateTime zdtLater = zdt.plus( d ) ;
Those classes also offer shortcut methods, if you wish.
ZonedDateTime zdtLater = zdt.plusHours( 4 ) ; // Alternative to using `Duration` object.
One benefit of using a Duration rather than the shortcut methods is having an object that can be named.
Duration halfShiftLater = Duration.ofHours( 4 ) ;
…
ZonedDateTime zdtLater = zdt.plus( halfShiftLater ) ;
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.
you can do something like
Calendar c = Calendar.getInstance();
c.setTimeInMillis(d2.getTime());
c.add(Calendar.HOUR_OF_DAY, 4);
d2 = c.getTime();
I recommend you using JDK8 time API or joda-time if you can.
Old java api for date is so bad!
In your case, you can:
//commons-lang3
Date oldDate = new Date();
Date newDate = DateUtils.addHours(oldDate, 1);
OR
convert date to timestamp, add some mills and convert timestamp back to date
I have date and time on string type 20/03/2018, 18:20:44 Is it possible to change it to date format in java? I tried this code:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
Date date = formatter.parse(dateString);
return date;
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
I get unable to parse exception and returned with null
You've used the wrong string replacements inside your simple date format, it should be dd/MM/yyyy, HH:mm:ss. Note the capitalisation of the HH as well, your time is in 24 hour format so it must be HH over hh
So with the applied changes your code will look like this:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
return formatter.parse(dateString);
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
Read more on the various patterns available here, as an aside it is generally recommended to use the ISO 8601 format for dates, so yours would be yyyy-MM-ddTHH:mm:ss
You should use the same format with input string:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
You did two mistakes :
mm represents minutes. MM represents months.
But You specify mm in the month part of the date format.
the coma character : , provided in the input has also to be present in the date format.
So with a String input in this form : "20/03/2018, 18:20:44", you should use this DateFormat :
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
tl;dr
Your formatting pattern was incorrect, using the wrong case and omitting the comma.
Also, you are using troublesome classes supplanted years ago by java.time classes.
LocalDateTime.parse( // Create a `LocalDateTime` object as the input string lacks any time zone or offset-from-UTC.
"20/03/2018, 18:20:44" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) // Define a formatting pattern to match the input.
)
.atZone( // Assign a time zone to the `LocalDateTime` to create a `ZonedDateTime` object.
ZoneId.of( "America/Los_Angeles" ) // Specify time zone to be assigned. Always use proper zone names `continent/region`; never use 3-4 character pseudo-zones.
)
2018-03-20T18:20:44-07:00[America/Los_Angeles]
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Parse your string as a LocalDateTime since it lacks an indicator of time zone or offset-from-UTC.
String input = "20/03/2018, 18:20:44" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2018-03-20T18:20:44
Lacking a time zone or offset-from-UTC means that this does not represent a moment, is not a point on the timeline. Without the context of a zone/offset, this represents only a vague idea about potential moments along a range of 26-27 hours.
Apparently you are certain this input was actually meant to be in certain time zone. Apply a ZoneId to this LocalDateTime to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Conversion
Best to avoid the troublesome legacy classes. But if you must produce a java.util.Date to inter-operate with old code not yet updated for java.time, you can convert. To convert back and forth, call new methods on the old classes.
A java.util.Date represents a point on the timeline in UTC, with a resolution of milliseconds. So its replacement in java.time is Instant. An Instant is also a point on the timeline in UTC, with a finer resolution of nanoseconds. To get to a Date, we need an Instant, which we can pull from our ZonedDateTime.
Instant instant = zdt.toInstant() ; // Same moment, same point on the timeline, different wall-clock time.
Now we can get the legacy class object, Date, by calling Date.from.
java.util.Date date = Date.from( instant ) ; // Do this only if you *must* work with `Date` class.
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.
I need to format a string date with given time zone and return the date object back. I am currently in IST time zone.
So IST is 5 hours and 30 minutes ahead of UTC.
public void getDate(){
String dateStr = "11/25/2016T13:30:00.000";
String dateFormat = "MM/dd/yyyy'T'HH:mm:ss.SSS";
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(date);
}
public static Date formatedStringToDate(final String date, final String dateFormat) throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsedDate = null;
if (date != null) {
try {
parsedDate = sdf.parse(date);
} catch (ParseException e) {
throw e;
}
}
return parsedDate;
}
I get the below out put.
Fri Nov 25 19:00:00 **IST** 2016
The time seems to be change from 5.30 hours but then if its a IST to UCT time converstion, it should be 5.30 hours before 13:30:00 which is 08:00:00?
Also how could I change the highlighted IST part of out put string to show the currect time zone in this case UTC?
When you call toString on a Date (by printing it) you get the default format (because a Date is an object that stores a number of milliseconds, or nanoseconds in Java 9+, since an epoch). To see the result in UTC you need something like,
final DateFormat sdf = DateFormat.getDateTimeInstance(DateFormat.FULL,
DateFormat.FULL);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(sdf.format(date)); // <-- format the Date
tl;dr
LocalDateTime.parse( "2017-11-25T13:30:00.000" )
.atZone( ZoneId.of( "Asia/Kolkata" ) )
2017-11-25T13:30+05:30[Asia/Kolkata]
java.time
The modern approach uses the java.time classes that replaced the troublesome old legacy date-time classes.
Parse your input string as a LocalDateTime given the lack of any indicator of zone or offset-from-UTC.
Using standard ISO 8601 format for such strings is preferred. The java.time classes use the standard formats by default when parsing/generating strings.
LocalDateTime ldt = LocalDateTime.parse( "2017-11-25T13:30:00.000" ) ;
ldt.toString(): 2017-11-25T13:30
If you are certain this date-time was intended to represent a moment by the wall-clock time of India, then assign a time zone to produce a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2017-11-25T13:30+05:30[Asia/Kolkata]
You can adjust into another zone for comparison.
ZonedDateTime zdtMontreal = zdt.withZoneSameInstant( ZoneId.of( "America/Montreal") );
zdtMontreal.toString(): 2017-11-25T03:00-05:00[America/Montreal]
To parse/generate strings in other formats such as the one in your Question, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Search Stack Overflow for more info, as these have been covered extensively.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu'T'HH:mm:ss.SSS" , Locale.US ) ;
Use that formatter for parsing.
LocalDateTime ldt = LocalDateTime.parse( "11/25/2016T13:30:00.000" , f ) ;
And for generating.
String output = ldt.format( f ) ; // Generate string.
Consider using ISO 8601 formats instead.
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'm trying to convert current time in MST using below code
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
TimeZone toTimeZone = TimeZone.getTimeZone("MST");
sdf.setTimeZone(toTimeZone);
Date date = new Date();
String strDate = sdf.format(date.getTime());
strDate displaying correct MST time, but after parsing it is giving wrong date time.
Date currentDate = sdf.parse(strDate);
I want current MST time in Date format not in string.
A java.util.Date object does not have a concept of time zone.
There is no way to set a timezone for a Date
There is no way to change the timezone of a Date object
A Date object created with the new Date() default constructor will be initialised with the current time in the system default timezone
All you did is add a time zone information for the formatting part... setTimeZone does not convert anything.
tl;dr
ZonedDateTime zdt = LocalDateTime.parse( input , DateTimeFormatter.forPattern( "dd/MM/uuuu hh:mm:ss" ) ).atZone( ZoneId.of( "America/Denver" ) );
Avoid legacy date-time classes
You are using old outmoded troublesome legacy date-time classes.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also 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.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
LocalDateTime
Your input string lacks any indication of offset-from-UTC or time zone. So we must parse as a LocalDateTime. A LocalDateTime has no offset or time zone, so it does not represent a moment on the timeline. Like saying "Christmas starts at midnight on December 25", that only has meaning (only becomes a point on the timeline) when you apply it to a particular time zone somewhere on the planet.
String input = …
DateTimeFormatter f = DateTimeFormatter.forPattern( "dd/MM/uuuu hh:mm:ss" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
ZonedDateTime
If you know the context and can assume the intended offset or time zone, you can create an OffsetDateTime or ZonedDateTime respectively.
Use proper time zone names, named in the format of continent/region. By MST perhaps you meant the America/Denver time zone used in much of the Rocky Mountains parts of the United States, or America/Edmonton used in parts of Canada.
Never use the 3-4 letter abbreviations such as MST. These abbreviations are not true time zones, are not standardized, and are not even unique(!).
ZoneId zoneId = ZoneId.of( "America/Denver" ) ;
ZonedDateTime zdt = ldt.atZone( zoneId ) ;
Converting
I suggest avoiding the notoriously troublesome java.util.Date class. But if you must do so , you may convert to/from java.time types. To interoperate with other code or libraries, convert using new methods added to the old classes. In this case, use a Instant object extracted from the OffsetDateTime or ZonedDatetime and pass to java.util.Date.from.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() ) ;
Going the other direction, use another new method added to the old class, java.util.Instant::toInstant.
Instant instant = utilDate.toInstant();
ZonedDateTime zdt = instant.atZone( zoneId ) ;