Rectangle 27 45

No Time Zone in j.u.Date

As the other correct answers stated, a java.util.Date has no time zone. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.

For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.

Instead use the java.time package bundled with Java 8. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. For Java 6 & 7, use the back-port project, ThreeTen-Backport. For Android, the adaptation of that back-port, ThreeTenABP. See Oracle Tutorial.

The java.time classes can represent a moment on the timeline in three ways:

Instant
OffsetDateTime
ZoneOffset
ZonedDateTime
ZoneId

In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instant objects for much of your business logic.

Instant instant = Instant.now();

Apply a ZoneOffset to get an OffsetDateTime.

ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );

Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).

Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.

String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]

For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the users expected human language and cultural norms. Or you can specify a particular format.

While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.

In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zones Daylight Saving Time (DST) and other such anomalies.

String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );

Call the toString method to generate a String in ISO 8601 format.

String output = dateTimeIndia.toString();

If required, you can convert from Joda-Time DateTime to a java.util.Date.

Java.util.Date date = dateTimeIndia.toDate();

Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString method in generating a string representation of the date-time value; instead the JVMs current default time zone is applied on-the-fly. So, as shorthand, we often say j.u.Date has no time zone. Confusing? Yes. Yet another reason to avoid these tired old classes.

"No Time Zone in j.u.Date" is wrong. There is a timezone information in j.u.Date stored in its BaseCalendar.Date cdate property if set. Take a look at the source code here. You can't set the timezone of a j.u.Date object except by changing the default timezone of the JVM by calling TimeZone.setDefault(TimeZone.getTimeZone("NEW_TIME_ZONE"));. Thus, there is a timezone offset and you can get the offset by calling the deprecated method j.u.Date.getTimezoneOffset()

@blquythai Correct, you did your homework. As did I, having seen that source code before. There is a time zone buried in there. But for all practical purposes that time zone is ignored. A java.util.Date works without any time zone, in effect being in UTC, while ignoring that buried time zone. Except for the toString method which applies the JVMs current default time zone; again ignoring the buried time zone. So for brevity, we say a java.util.Date has no time zone. Like Art, it's a lie that tells the truth.

@blquythai As for calling TimeZone.setDefault, you are not setting the time zone of the java.util.Date object -- the Date object still ignores its buried time zone, acting effectively in UTC. You would affect Dates toString method. Setting the default changes the JVMs default time zone which is usually set to the host operating systems time zone. That call is not recommended as it affects all the code in all the threads of all the apps running in that JVM, and does so on-the-fly as they are executing. Being rude and dangerous, that call should only be considered as a last resort.

That time zone is used very often (used in equals, hashcode, getTime..) If you take a look at the equals method, it calls getTime() which calls getTimeImpl(), which calls normalize() if the cdate property is not normalized. In normalize() method, the last if condition re-calculates the milliseconds since 1/1/70 based on its stored timezone information if the timezone of cdate is different from the timezone of the current JVM environment it is running on. (Take a look at sun.util.calendar.AbstractCalendar getCalendarDate(long millis, CalendarDate date))

Well, we are engineers, not artists here (though many claim that programming is a form of art), so in my humble opinion it would be fair to at least leave a few words of disclaimer... No downvote, but in such a well and detailed answer I think it should be included.

How to set time zone of a java.util.Date? - Stack Overflow

java date timezone java.util.date
Rectangle 27 3

I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format.

No, you have a Date variable. That doesn't have any particular format. Ignore what toString() tells you - that's just formatting it in your local time zone, in a default format. That doesn't mean the format or time zone is part of the state of the Date object - that just represents a point in time.

// Whatever pattern you want - ideally, specify the locale too
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Whatever time zone you want
format.setTimeZone(...);
String text = format.format(date);

Alternatively, if you just want a Calendar value:

TimeZone zone = ...; // Whatever time zone you want
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
// Now use calendar.get(Calendar.YEAR) etc

The dates are being stored in the -7:00 GMT format. I need to validate some values against those dates. But when I try to get the calendar date, the date gets modified to my current timezone. Is there a way to by pass that? Also can I give the timezone as -7:00 or +5:30 (or will have to search a timezone that matches to the particular value)?

@LakshitPande: "The dates are being stored in the -7:00 GMT format." Not in java.util.Date they're not. In java.util.Date, they're stored as a long value, which is the number of milliseconds since the unix epoch. I've given you code which will either display the value in whatever time zone you want, or give you a Calendar object you can use. It's not clear whether you've tried that code or not, or where your Date has come from. Use SimpleTimeZone to construct a time zone with a fixed offset - but be aware that that probably won't be useful in many places, as it won't observe DST.

thanks for the info. I did not properly understand the answer. The comments help. Thanks again. It works.

How to get calender date from a date field in Java in a particular tim...

java date datetime timezone
Rectangle 27 3

I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format.

No, you have a Date variable. That doesn't have any particular format. Ignore what toString() tells you - that's just formatting it in your local time zone, in a default format. That doesn't mean the format or time zone is part of the state of the Date object - that just represents a point in time.

// Whatever pattern you want - ideally, specify the locale too
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Whatever time zone you want
format.setTimeZone(...);
String text = format.format(date);

Alternatively, if you just want a Calendar value:

TimeZone zone = ...; // Whatever time zone you want
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
// Now use calendar.get(Calendar.YEAR) etc

The dates are being stored in the -7:00 GMT format. I need to validate some values against those dates. But when I try to get the calendar date, the date gets modified to my current timezone. Is there a way to by pass that? Also can I give the timezone as -7:00 or +5:30 (or will have to search a timezone that matches to the particular value)?

@LakshitPande: "The dates are being stored in the -7:00 GMT format." Not in java.util.Date they're not. In java.util.Date, they're stored as a long value, which is the number of milliseconds since the unix epoch. I've given you code which will either display the value in whatever time zone you want, or give you a Calendar object you can use. It's not clear whether you've tried that code or not, or where your Date has come from. Use SimpleTimeZone to construct a time zone with a fixed offset - but be aware that that probably won't be useful in many places, as it won't observe DST.

thanks for the info. I did not properly understand the answer. The comments help. Thanks again. It works.

How to get calender date from a date field in Java in a particular tim...

java date datetime timezone
Rectangle 27 438

It depends on what form of date / time you want:

If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone ... assuming that the system clock has been set correctly.

If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations. With Java 8, this is no longer true. However, if you are already using Joda time in your codebase, there is no strong1 reason to migrate.

Just as a warning, Joda-time is great, but initial creation of a Joda-time object can take a long time. See: stackoverflow.com/questions/6280829/

@Stephen What did you mean by "This value is a delta from a UTC time-point, and is independent of the local time-zone"?

@Geek - System.currentTimeMillis() value is approximately UTC, and there is probably a difference (delta) between the local UTC clock and true UTC. System.currentTimeMillis() is independent of the local timezone ... well ... because it is UTC, and UTC is the same irrespective of the local time-zone of the computer, the user or anything else.

Please consider new Java8 APIs - LocalDateTime.now() and ZonedDateTime.now()

datetime - How to get the current date/time in Java - Stack Overflow

java datetime
Rectangle 27 146

Instant.now()

Generate a String to represent that value:

Instant.now().toString()

As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone. But its toString implementation applies the JVMs default time zone when generating the String representation of that date-time value. Confusingly to the nave programmer, a Date seems to have a time zone but does not.

The java.util.Date, j.u.Calendar, and java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:

  • java.time.* package in Java 8

Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.

Getting current time in UTC/GMT is a simple one-liner

Instant instant = Instant.now();

That Instant class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.

In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computers clock hardware.

Its toString method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.

If you want more flexible formatting, adjustments in or out of various time zones, or other additional features, then apply a time zone (ZoneId object) to get a ZonedDateTime. The time zone can be for UTC or any other time zone. The subclass of ZoneId, ZoneOffset holds a constant for UTC.

ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC );
System.out.println( "now: " + now );
now: 2014-01-21T23:42:03.522Z

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.

Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.

System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );
org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );
System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );
Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z

I recommend you always specify a time zone rather than relying implicitly on the JVMs current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.

When calling now() pass the desired/expected time zone to be assigned. Use the DateTimeZone class.

DateTimeZone zoneMontral = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontral );
DateTime now = DateTime.now( DateTimeZone.UTC );

If you truly want to use the JVMs current default time zone, make an explicit call so your code is self-documenting.

DateTimeZone zoneDefault = DateTimeZone.getDefault();

Read about ISO 8601 formats. Both java.time and Joda-Time use that standards sensible formats as their defaults for both parsing and generating strings.

Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Dates toString method; that method uses the JVMs current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.

DateTime.now().toDateTime(DateTimeZone.UTC)
DateTime nowUtc = DateTime.now ( DateTimeZone.UTC ) ;
zoneMontral

How can I get the current date and time in UTC or GMT in Java? - Stack...

java date localization timezone gmt
Rectangle 27 143

Instant.now()

Generate a String to represent that value:

Instant.now().toString()

As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone. But its toString implementation applies the JVMs default time zone when generating the String representation of that date-time value. Confusingly to the nave programmer, a Date seems to have a time zone but does not.

The java.util.Date, j.u.Calendar, and java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:

  • java.time.* package in Java 8

Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.

Getting current time in UTC/GMT is a simple one-liner

Instant instant = Instant.now();

That Instant class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.

In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computers clock hardware.

Its toString method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.

If you want more flexible formatting, adjustments in or out of various time zones, or other additional features, then apply a time zone (ZoneId object) to get a ZonedDateTime. The time zone can be for UTC or any other time zone. The subclass of ZoneId, ZoneOffset holds a constant for UTC.

ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC );
System.out.println( "now: " + now );
now: 2014-01-21T23:42:03.522Z

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.

Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.

System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );
org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );
System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );
Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z

I recommend you always specify a time zone rather than relying implicitly on the JVMs current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.

When calling now() pass the desired/expected time zone to be assigned. Use the DateTimeZone class.

DateTimeZone zoneMontral = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontral );
DateTime now = DateTime.now( DateTimeZone.UTC );

If you truly want to use the JVMs current default time zone, make an explicit call so your code is self-documenting.

DateTimeZone zoneDefault = DateTimeZone.getDefault();

Read about ISO 8601 formats. Both java.time and Joda-Time use that standards sensible formats as their defaults for both parsing and generating strings.

Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Dates toString method; that method uses the JVMs current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.

DateTime.now().toDateTime(DateTimeZone.UTC)
DateTime nowUtc = DateTime.now ( DateTimeZone.UTC ) ;
zoneMontral

How can I get the current date and time in UTC or GMT in Java? - Stack...

java date localization timezone gmt
Rectangle 27 1

EST is not a time zone

The 3-4 letter pseudo-zones seen in the media are not true time zones. They are not standardized, and are not even unique(!).

continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
ZoneId z = ZoneId.of( "America/New_York" );

When possible, avoid using XMLGregorianCalendar. Like the legacy Date & Calendar & GregorianCalendar classes, these are now supplanted by the superior java.time classes.

Bad practice to depend on the host OS default time zone as that is out of your control as a programmer.

Similarly bad practice to depend on the JVMs current default time zone as that is also outside your control. Any code in any thread of any app within the JVM can change the current default during runtime.

Sounds like your people are expecting to use the host OS current default time zone as a signal to alter your apps behavior. Very strange and clumsy strategy. You have so many other routes available: configuration files, JMX, JNDI, and so on.

I know of no way for the JVM to directly access the host OS current default time zone. You could go some roundabout way via command-line utility or some such.

You can get the JVMs current default. Most implementations of Java with which I am familiar set the JVMs to the host OS default, by default.

ZoneId z = ZoneId.systemDefault() ;

If you are given a XMLGregorianCalendar object, convert to java.time.ZonedDateTime via GregorianCalendar.

GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
ZonedDateTime zdt = gc.toZonedDateTime() ;

From that ZonedDateTime extract a 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).

Instant instant = zdt.toInstant() ;
OffsetDateTime
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
String outputDate = odt.toLocalDate().toString() ;
String outputTime = odt.toLocalTime().toString() ;

For a time zone rather than mere offset-from-UTC, use ZonedDateTime. For east coast of US, perhaps you want America/New_York.

ZonedDateTime zdt = instant.atZone( ZoneId.of( "America/New_York" ) ) ;

Generate strings in standard ISO 8601 format.

String outputDate = zdt.toLocalDate().toString() ;
String outputTime = zdt.toLocalTime().toString() ;

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.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

java - Timezone issue: convert to UTC if JVM timezone is in UTC - Stac...

java timezone java-7 timestamp-with-timezone
Rectangle 27 8

Instant.now()
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )

A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.

The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being yesterday in Montral Qubec.

Much of your business logic and data storage/exchange should be done in UTC, as a best practice. To get the current moment in UTC with a resolution in nanoseconds, use Instant class.

Instant instant = Instant.now();

You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

We can skip the Instant and get the current ZonedDateTime directly.

ZonedDateTime zdt = ZonedDateTime.now( z );

Always pass that optional time zone argument. If omitted, your JVMs current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.

ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.

You can later extract an Instant from the ZonedDateTime.

Instant instant = zdt.toInstant();

Always use an Instant or ZonedDateTime rather than a LocalDateTime when you want an actual moment on the timeline. The Local types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the Local types into a ZonedDateTime and thereby make it meaningful.

The LocalDate class represents a date-only value without time-of-day and without time zone.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );  // Always pass a time zone.

To generate a String representing the date-time value, simply call toString on the java.time classes for the standard ISO 8601 formats.

String output = myLocalDate.toString();  // 2016-09-23
String output = zdt.toString();  // 2016-09-23T12:34:56.789+03:00[America/Montreal]

The ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.

For other formats, search Stack Overflow for many Questions and Answers on the DateTimeFormatter class.

Contrary to the comment on the Question by RamanSB, you should not use LocalDateTime class for the current date-time.

The LocalDateTime purposely lacks any time zone or offset-from-UTC information. So, this is not appropriate when you are tracking a specific moment on the timeline. Certainly not appropriate for capturing the current moment.

The Local wording is counter-intuitive. It means any locality rather than any one specific locality. For example Christmas this year starts at midnight on the 25th of December: 2017-12-25T00:00:00, to be represented as a LocalDateTime. But this means midnight at various points around the globe at different times. Midnight happens first in Kiribati, later in New Zealand, hours more later in India, and so on, with several more hours passing before Christmas begins in France when the kids in Canada are still awaiting that day. Each one of these Christmas-start points would be represented as a separate ZonedDateTime.

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.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

@PeterMortensen FYI, Stack Overflow discourages changes done only for trivial copy-editing. Also, none of your edits were for accidents or typos; all were intentionally written by me. I do appreciate any fixes for content, bugs, or poor communication.

datetime - How to get the current date/time in Java - Stack Overflow

java datetime
Rectangle 27 3

To store a UTC TIMESTAMP in your DB, you need to create a Java Timestamp that represents the date of your report (say 8th November 7pm UTC), but in the local time zone without conversion (say 8th November 7pm CET). So your approach is correct: get the LocalDateTime of the analysis date in UTC (8th November 7pm) and create a Timestamp in your local time zone at that LocalDateTime.

I don't think there is a shorter/better way to do it. If you used a sql TIMESTAMP WITH TIME ZONE field you would not have to do any manipulations and Date.from(Instant) would produce the correct result.

Clarification of the concepts involved, using the time at which you posted your question as an example (Sunday 8th November 2015 at 7pm UTC) and assuming your local time zone is CET (Central European Time = UTC+1):

  • the Java Timestamp will be the number of milliseconds since the epoch, i.e. it represents the unique instant on the time line at which you posted your question and does not have any time zone information
  • when storing that Timestamp into a TIMESTAMP (i.e. without time zone) field, the jdbc driver will calculate the date/time corresponding to your Timestamp in the default time zone (unless a Calendar is explicitly provided) - so your DB will show Sunday 8th November at 8pm
  • a java.time.Instant is similar to a Java Timestamp: it represents a unique point in time, without time zone information
  • a LocalDateTime is like a sql TIMESTAMP, it says, for example, Sunday 8th November 8pm, but you don't know what point in time that is without additional time zone information
  • a ZonedDateTime is essentially a LocalDateTime + a time zone. For example Sunday 8th November 8pm [Europe/Paris] - that generally identifies a unique instant but not necessarily (think of when clocks change backward for DST and the same hour is repeated twice).
  • an OffsetDateTime is essentially a LocalDateTime + an offset vs. UTC. For example Sunday 8th November 8pm +01:00. That identifies a unique instant in time.

The standard approach is generally to store an instant as a sql TIMESTAMP WITH TIME ZONE and use either a Timestamp or an OffsetDateTime on the Java side of things.

Is this the correct way to obtain a java.sql.Timestamp at UTC from a D...

java java-8 java-time
Rectangle 27 21

Instant.now()  // Current moment in UTC.

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

The other Answers, while correct, are outdated. The old date-time classes have proven to be poorly designed, confusing, and troublesome.

Those old classes have been supplanted by the java.time framework.

  • Java 8 and later: The java.time framework is built-in.

These new classes are inspired by the highly successful Joda-Time project, defined by JSR 310, and extended by the ThreeTen-Extra project.

An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.

Instant instant = Instant.now(); // Current moment in UTC.

Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVMs current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.

Use proper time zone names in the format of continent/region such as America/Montreal, Europe/Brussels, or Asia/Kolkata. Never use the 3-4 letter abbreviations such as EST or IST as they are neither standardized nor unique.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.

You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.

String output = instant.toString();

Note that for ZonedDateTime, the toString method extends the ISO 8601 standard by appending the name of the time zone in square brackets. Extremely useful and important information, but not standard.

Or specify your own particular formatting pattern with the DateTimeFormatter class.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

Better yet, let java.time do the work of localizing automatically.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

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, & java.text.SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

@giraffe.guru Reread my Answer. You missed the third bullet. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Get current time and date on Android - Stack Overflow

android date time
Rectangle 27 20

Instant.now()  // Current moment in UTC.

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

The other Answers, while correct, are outdated. The old date-time classes have proven to be poorly designed, confusing, and troublesome.

Those old classes have been supplanted by the java.time framework.

  • Java 8 and later: The java.time framework is built-in.

These new classes are inspired by the highly successful Joda-Time project, defined by JSR 310, and extended by the ThreeTen-Extra project.

An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.

Instant instant = Instant.now(); // Current moment in UTC.

Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVMs current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.

Use proper time zone names in the format of continent/region such as America/Montreal, Europe/Brussels, or Asia/Kolkata. Never use the 3-4 letter abbreviations such as EST or IST as they are neither standardized nor unique.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.

You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.

String output = instant.toString();

Note that for ZonedDateTime, the toString method extends the ISO 8601 standard by appending the name of the time zone in square brackets. Extremely useful and important information, but not standard.

Or specify your own particular formatting pattern with the DateTimeFormatter class.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

Better yet, let java.time do the work of localizing automatically.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

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, & java.text.SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

@giraffe.guru Reread my Answer. You missed the third bullet. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Get current time and date on Android - Stack Overflow

android date time
Rectangle 27 20

Instant.now()  // Current moment in UTC.

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

The other Answers, while correct, are outdated. The old date-time classes have proven to be poorly designed, confusing, and troublesome.

Those old classes have been supplanted by the java.time framework.

  • Java 8 and later: The java.time framework is built-in.

These new classes are inspired by the highly successful Joda-Time project, defined by JSR 310, and extended by the ThreeTen-Extra project.

An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.

Instant instant = Instant.now(); // Current moment in UTC.

Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVMs current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.

Use proper time zone names in the format of continent/region such as America/Montreal, Europe/Brussels, or Asia/Kolkata. Never use the 3-4 letter abbreviations such as EST or IST as they are neither standardized nor unique.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.

You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.

String output = instant.toString();

Note that for ZonedDateTime, the toString method extends the ISO 8601 standard by appending the name of the time zone in square brackets. Extremely useful and important information, but not standard.

Or specify your own particular formatting pattern with the DateTimeFormatter class.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

Better yet, let java.time do the work of localizing automatically.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

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, & java.text.SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

@giraffe.guru Reread my Answer. You missed the third bullet. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Get current time and date on Android - Stack Overflow

android date time
Rectangle 27 2

Since you have tagged your question java-time, you do deserve a java.time answer.

String dateAndTime = "20140508063630";
    DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    ZonedDateTime coralHarbourDateTime = LocalDateTime.parse(dateAndTime, parseFormatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("America/Coral_Harbour"));
    System.out.println(coralHarbourDateTime);
2014-05-08T01:36:30-05:00[America/Coral_Harbour]

There are a number of things to note though:

  • You also tagged your question android. java.time seems to be coming to Android, but as of writing it is not on the majority of Android phones. Don t despair, though, get the ThreeTenABP and use the classes on Android.
  • The SimpleDateFormat and TimeZone classes used in the other answers are long outdated, so if your Android app is doing any work with dates and/or times and/or time zones, I do recommend ThreeTenABP and the modern classes as the programmer friendly and the futureproof way to go.
  • You asked for EST time zone and then gave us a date of May 8, which is in the summer time (DST) part of the year. First, three letter abbreviations are dangerous in being ambiguous and in this case not a full time zone, so avoid them where you can. I solved the problem by using America/Coral_Harbour since I read that this particular place uses EST all year round, no summer time. If this was not what you intended, please provide a different location. If instead I use America/Montreal, I get 2014-05-08T02:36:30-04:00[America/Montreal], for example, with time zone offset -4 instead of -5.

java - How to convert a time from GMT to EST - Stack Overflow

java android date timezone java-time
Rectangle 27 2

Since you have tagged your question java-time, you do deserve a java.time answer.

String dateAndTime = "20140508063630";
    DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    ZonedDateTime coralHarbourDateTime = LocalDateTime.parse(dateAndTime, parseFormatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("America/Coral_Harbour"));
    System.out.println(coralHarbourDateTime);
2014-05-08T01:36:30-05:00[America/Coral_Harbour]

There are a number of things to note though:

  • You also tagged your question android. java.time seems to be coming to Android, but as of writing it is not on the majority of Android phones. Don t despair, though, get the ThreeTenABP and use the classes on Android.
  • The SimpleDateFormat and TimeZone classes used in the other answers are long outdated, so if your Android app is doing any work with dates and/or times and/or time zones, I do recommend ThreeTenABP and the modern classes as the programmer friendly and the futureproof way to go.
  • You asked for EST time zone and then gave us a date of May 8, which is in the summer time (DST) part of the year. First, three letter abbreviations are dangerous in being ambiguous and in this case not a full time zone, so avoid them where you can. I solved the problem by using America/Coral_Harbour since I read that this particular place uses EST all year round, no summer time. If this was not what you intended, please provide a different location. If instead I use America/Montreal, I get 2014-05-08T02:36:30-04:00[America/Montreal], for example, with time zone offset -4 instead of -5.

java - How to convert a time from GMT to EST - Stack Overflow

java android date timezone java-time
Rectangle 27 15

'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

according to the documentation. That means, the time portion of the date-time is being cleared from your java.util.Date or Joda-Time DateTime objects.

As the correct answer by Gilbert Le Blanc notes, both java.util.Date and java.sql.Date have no concept of time zone internally. They store the number of milliseconds since the Unix epoch.

Those classes pull a nasty trick: Their toString methods apply your JVM's default time zone to the rendering of the string. Very confusing. The Date object has no time zone, yet when displayed as a string you see a time zone.

If your java.util.Date object contains the number of 1344902399000L milliseconds since the epoch (1970 start), that means 2012-08-13T23:59:59.000Z in UTC/GMT. But if your JVM believes itself to be in France with Daylight Saving Time (DST) in effect, you'll see 2 hours ahead of UTC/GMT: 2012-08-14T01:59:59.000+02:00 described in that class' awful string format. The same moment of time has different day-of-month meaning (13 vs 14) in different time zones, with the clock-on-the-wall being past midnight.

The Joda-Time 2.4 library can be helpful here. Pass either the java.sql.Date or java.util.Date object to a DateTime constructor along with the UTC time zone object to get a clear picture of the value with which you are struggling.

java.util.Date date = new java.util.Date( 1390276603054L );
DateTime dateTimeUtc = new DateTime( date, DateTimeZone.UTC );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
2014-01-21T03:56:43.054Z
java.util.Date date = myDateTime.toDate();

To convert the other direction from Joda-Time to java.sql.Date

java.sql.Date date = new java.sql.Date( myDateTime.getMillis() );

The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

The equivalent of java.util.Date is 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).

Instant instant = Instant.ofEpochMilli( 1390276603054L );
ZoneId
ZonedDateTime
java.util.Calendar
DateTime
ZoneId z = ZoneId.of( "Europe/Kaliningrad" );
ZonedDateTime zdt = instant.atZone( z );

Now extract a date-only value, the date portion of that ZonedDateTime, as a LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone. So LocalDate is what java.sql.Date is pretending to be: a date-only value.

LocalDate localDate = zdt.toLocalDate() ;

In JDBC 4.2 and later, you can use the java.time types directly with a compliant driver via PreparedStatement::setObject and ResultSet::getObject.

myPreparedStatement.setObject(  , localDate );
LocalDate ld = myResultSet.getObject(  , LocalDate.class );

For an older non-compliant driver, convert briefly to a java.sql.Date object to/from a LocalDate by using new methods added to the old class: toLocalDate and valueOf( LocalDate ).

@thomas.mc.work No, going from a Joda-Time DateTime object to a java.util.Date is much easier than that just call the toDate method. Like this: java.util.Date date = myDateTime.toDate();. For a java.**sql**.Date, you were close but don't need the UTC as Millis are always UTC. So: java.sql.Date date = new java.sql.Date( myDateTime.getMillis() );

But when i convert java.sql.Date from database with the value "2014-02-01" in this way then i get "2014-01-31T23:00:00.000Z" (my time zone is CET). When i use the time zone CET then it is correct: "2014-02-01T00:00:00.000Z". Why is that?

@thomas.mc.work (a) Avoid those three-letter time zone codes like "CET". User a proper time zone name. (b) When parsing string to DateTime, pass the time zone in which to frame the time or else your JVM's default is used. Example: DateTime dateTime = new DateTime( "2014-02-01", DateTimeZone.forID( "Europe/Berlin" ) ); 2014-02-01T00:00:00.000+01:00 (c) Germany is 1 hour ahead of UTC. So the first moment of the day 00:00:00 in Hanover is 23:00:00 the previous day in UTC. Being "ahead" of UTC means moving backwards to UTC.

Convert joda.time.DateTime to java.sql.Date and retain time zone - Sta...

java date jdbc jodatime
Rectangle 27 12

Servers in UTC

Yes, generally servers should have their OS set to UTC as the time zone, or if not provided use GMT or the Reykjavk Iceland time zone. Your Java implementation probably picks up this setting as its own current default time zone.

But do not depend on the time zone being set to UTC. A sysadmin could change it. And any Java code in any thread of any app within your JVM can change the JVMs current default time zone at runtime by calling TimeZone.setDefault. So instead, make a habit of always specifying the desired/expected time zone by passing the optional argument in your Java code.

I consider it a design flaw that any date-time framework would make the time zone optional. Being optional creates endless amounts of confusion because programmers, like everybody else, unconsciously think in terms of their own personal time zone unless prompted. So all too often in date-time work no attention is paid to the issue. Add on the problem that the JVM default varies. By the way, ditto for Locale, same problems, should always be specified explicitly.

Your business logic, data storage, and data exchange should almost always be done in UTC. Nearly every database has a feature for adjusting any input into UTC and storing in UTC.

When presenting a date-time to a user, adjust into the expected time zone. When serializing a date-time value, use the ISO 8601 string formats. See the Answer by VickyArora for Oracle specifically (I am a Postgres person). Be sure to read the doc carefully, and practice by experimenting to fully understand your database's behavior. The SQL spec does not spell out very much in this regard, and behavior varies widely.

Remember that when using Java and JDBC, you will be using the java.sql.Timestamp and related data types. They are always in UTC, automatically. In the future expect to see JDBC drivers updated to directly use the new data types defined in the java.time framework built into Java 8 and later.

The old classes are outmoded by java.time. Learn to use java.time while avoiding the old java.util.Date/.Calendar and make your programming life much more pleasant.

Until your JDBC driver is updated, you can use the conversion convenience methods built into java.time. See examples next, where Instant is a moment in UTC and ZonedDateTime is an Instant adjusted into a time zone.

Instant instant = myJavaSqlTimestamp.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

To go the other direction.

java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( zdt.toInstant() );

If your business requirements consider the original input datas time zone to be important, to be remembered, then store that explicitly as a separate column in your database table. You can use an offset-from-UTC, but that does not provide full information. A time zone is an offset plus a set of rules for the past, present, and future handling of anomalies such as Daylight Saving Time. So a proper time zone name is most appropriate such as America/Montreal.

You said you collect many date-only values, without time-of-day and without time zone. The class for that in java.time is LocalDate. As with LocalTime and LocalDateTime, the Local part means no particular locality, so therefore no time zone, and so not a point on the timeline -- has no real meaning.

Keep in mind that a date-only value is ambiguous by definition. At any given moment, the date varies around the world. For example, just after midnight in Paris France is a new day but in Montral Qubec the date is still yesterday.

Usually in business some time zone is implicit, even unconsciously intuited. Unconscious intuition about data points tends not to work well over the long term, especially in software. Better to make explicit what time zone was intended. You could store the intended zone alongside the date such as another column in database table, or your could make a comment in your programming code. I believe it would vastly better and safer to store a date-time value. So how do we transform a date-only into a date-time?

Often a new day is the moment after midnight, the first moment of the day. You might think that means the time-of-day 00:00:00.0 but not always. Daylight Saving Time (DST) and possibly other anomalies may push the first moment to a different wall-clock time. Let java.time determine the correct time-of-day for first moment going through the LocalDate class and its atStartOfDay method.

In some business contexts a new day may be defined (or assumed) to be business hours. For example, say a publisher in New York means 9 AM in their local time when they say the book draft is due by January 2nd. Let's get that time-of-day for that date in that time zone.

ZoneId zoneId = ZoneId.of( "America/New_York" );
ZonedDateTime zdt = ZonedDateTime.of( 2016 , 1 , 2 , 9 , 0 , 0 , 0 , zoneId );

What does that mean for the author working in New Zealand? Adjust into her particular time zone for presentation to her by calling withZoneSameInstant.

ZoneId zoneId_Pacific_Auckland = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt_Pacific_Auckland = zdt.withZoneSameInstant( zoneId_Pacific_Auckland );

For database storage we transform into an Instant (a moment on the timeline in UTC) and pass as a java.sql.Timestamp as seen earlier above.

java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );

When retrieved from the database, transform back to a New York date-time. Convert from java.sql.Timestamp to an Instant, then apply a time zone ZoneId to get a ZonedDateTime.

Instant instant = ts.toInstant();
ZoneId zoneId = ZoneId.of( "America/New_York" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

If your database driver complies with JDBC 4.2 or later, you may be able to pass/fetch the java.time types directly rather than convert to/from java.sql types. Try the PreparedStatement::setObject and ResultSet::getObject methods.

java - Handling time zone in web application - Stack Overflow

java oracle date datetime timezone
Rectangle 27 1

You have to use TimeZone class and Calendar class.

Calendar currentdatetime = Calendar.getInstance();

Just pass your time zone name in TimeZone class like this :

TimeZone.getTimeZone("EST");
DateFormater
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatter.setTimeZone(obj);

and get output like this :

System.out.println("EST Time is : "+ formatter.format(currentdatetime .getTime())

java - How to convert date and time to est format in android? - Stack ...

java android timezone
Rectangle 27 21

If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate class rather than java.util.Date.

In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

A SQL data type DATE is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class until java.time.LocalDate in Java 8. Let's create such a value by getting today's date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montral, for example).

LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );  // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".

At this point, we may be done. If your JDBC driver complies with JDBC 4.2 spec, you should be able to pass a LocalDate via setObject on a PreparedStatement to store into a SQL DATE field.

myPreparedStatement.setObject( 1 , localDate );

Likewise, use ResultSet::getObject to fetch from a SQL DATE column to a Java LocalDate object. Specifying the class in the second argument makes your code type-safe.

LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );

If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.

java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );

And going the other direction.

LocalDate localDate = sqlDate.toLocalDate();

While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.

Go through the Instant class, which represents a moment on the timeline in UTC. An Instant is similar in idea to a java.util.Date. But note that Instant has a resolution up to nanoseconds while java.util.Date has only milliseconds resolution.

To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant ) and java.util.Date::toInstant.

Instant instant = myUtilDate.toInstant();

To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();

The java.sql.Date class pretends to be date-only without a time-of-day but actually does a time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to convert java.util.Date to java.sql.Date? - Stack Overflow

java sql datetime date
Rectangle 27 18

Instant.now()
       .toString()
ZonedDateTime.now( 
    ZoneId.of( "America/Montreal" ) 
).format(  DateTimeFormatter.ISO_LOCAL_DATE_TIME )
 .replace( "T" , " " )

In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.

If you want to eliminate any microseconds or nanoseconds from your data, truncate.

Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;

The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.

An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computers hardware clocks abilities.

Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();

Replace the T in the middle with a space, and the Z with nothing, to get your desired output.

String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.

As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.

String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );

The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.

The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.

System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
Now: 2013-11-26T20:25:12.014Z

Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:

int millisOfSecond = myDateTime.getMillisOfSecond ();

date - How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond...

java date
Rectangle 27 4

LocalDateTime.parse(     // Parse string as value without time zone.
    "2017-01-23 12:34 PM" , 
    DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" )
).atZone( ZoneId.of( "America/Montreal" ) )  // Assign time zone.
 .toString()             // Generate string: 2017-01-23T17:34:00Z
 .replace( "T" , " " )   // Substitute SPACE for 'T' in middle.
 .replace( "Z" , " Z" )  // Insert SPACE before 'Z'.

The other Answers use the troublesome old date-time classes (Date, Calendar, etc.), now legacy, supplanted by the java.time classes.

I have a string in the pattern yyyy-MM-dd hh:mm a

Such an input string lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime.

Define a formatting pattern to match your input with a DateTimeFormatter object.

String input = "2017-01-23 12:34 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );

Note that a LocalDateTime is not a specific moment, only a vague idea about a range of possible moments. For example, a few minutes after midnight in Paris France is still yesterday in Montral Canada. So without the context of a time zone such as Europe/Paris or America/Montreal, just saying a few minutes after midnight has no meaning.

and i can get the time zone object separately in which the above string represents the date.

A time zone is represented by the ZoneId class.

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/Montreal" );

Apply the ZoneId to get a ZonedDateTime which is indeed a point on the timeline, a specific moment in history.

ZonedDateTime zdt = ldt.atZone( z );

First, know that a Z literal character is short for Zulu and means UTC. In other words, an offset-from-UTC of zero hours, +00:00.

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).

You can extract a Instant object from a ZonedDateTime.

Instant instant = zdt.toInstant();  // Extracting the same moment but in UTC.

To generate a string in standard ISO 8601 format, such as 2017-01-22T18:21:13.354Z, call toString. The standard format has no spaces, uses a T to separate the year-month-date from the hour-minute-second, and appends the Z canonically for an offset of zero.

String output = instant.toString();

I strongly suggest using the standard formats whenever possible. If you insist on using spaces as in your stated desired format, either define your own formatting pattern in a DateTimeFormatter object or just do a string manipulation on the output of Instant::toString.

String output = instant.toString()
                       .replace( "T" , " " )  // Substitute SPACE for T.
                       .replace( "Z" , " Z" ); // Insert SPACE before Z.

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.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

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.

java - Converting string to date with timezone - Stack Overflow

java date timezone format