Converting string to 'timestamp with timezone' in java - java

I have a string "2016-07-21T21:30:47.492+0000" I want to save it in DB in a column that has the datatype 'TIMESTAMP WITH TIMEZONE'. Kindly suggest the solution.
This is what I did:
final SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSX");
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
final Date d1 = mdyFormat.parse(strDate);
final String mdx = sdf.format(d1);

You are using troublesome old classes now supplanted by java.time classes.
Here is how to follow the advice given by Jon Skeet posted in a comment on the Question.
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. The Joda-Time team 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.
OffsetDateTime
You can parse that input string as an OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2016-07-21T21:30:47.492+0000" );
If your JDBC driver complies with JDBC 4.2 or later, you may be able to pass/fetch to SQL via the PreparedStatement::setObject and ResultSet::getObject methods. If not, convert to the old java.sql type.
Converting requires an Instant object. An Instant is a more basic building-block class in java.time, lacking the flexibility of an OffsetDateTime. The Instant class represents a moment on the timeline in UTC with a resolution up to nanoseconds. Extract an Instant from that OffsetDateTime.
Instant instant = odt.toInstant();
Pass the Instant to a new method added to the old java.sql class.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
Then call the PreparedStatement::setTimestamp and ResultSet::getTimestamp methods.
myPreparedStatement.setTimestamp( 1 , ts );
…
java.sql.Timestamp ts = myResultSet.getTimestamp( 1 );
After fetching a java.sql.Timestamp, immediately convert to a java.time class, Instant. Use the java.sql classes only where direct support for java.time types is lacking in your JDBC driver, and even then, minimize your use of the java.sql classes. Do your business logic work in java.time.
Instant instant = ts.toInstant();
Confusing class names
Do not confuse the two old Date classes bundled with Java. The java.util.Date represents a date and a time-of-day. A java.sql.Date is intended to represent only a date-only value without a time-of-day (but confusing actually does have a time-of-day due to it being a clumsy hack of an awkward class design).
Avoid the java.util.Date and java.util.Calendar and java.text.SimpleDateFormat classes entirely. And minimize your use of the java.sql.Date/.Time/.Timestamp classes as discussed above.

Your code is having one problem
String strDate = "2016-07-21T21:30:47.492+0000";
final SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSX");
// include `T` as well
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
final Date d1;
try {
d1 = mdyFormat.parse(strDate);
// to add time zone you can use below line
// sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String mdx = sdf.format(d1);
System.out.println(mdx);
} catch (ParseException ex) {
}
Output without sdf.setTimeZone(TimeZone.getTimeZone("UTC"))
22-07-2016
Output with sdf.setTimeZone(TimeZone.getTimeZone("UTC"))
21-07-2016
TimeZone.getDefault() gets the system's default timezone.

Related

Add n number of days using simpledateformat in java

We have a java code snippet here
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
int days = 5;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date.getTime() + (days*86400000));
System.out.println(strDate);
}
}
to add n no. of days to today's date. The result will be correct upto n=24 but gives previous month' after n=24. Why it is so?
The problem is the the int is overflowing
consider
int days = 25;
int d = days*86400000;
System.out.println(d);
try
int days = 25;
long d = days*86400000L;
System.out.println(d);
tl;dr
LocalDate // Represent a date-only, without a time-of-day and without a time zone.
.now() // Capture the current date, as seen through your JVM’s current default time zone. Better to pass a `ZoneId` as the optional argument.
.plusDays( 5 ) // Add five days, returning a new `LocalDate` object. Per the Immutable Objects pattern, a new object is produced rather than changing (“mutating”) the original.
.format( // Generate text representing the date value of our `LocalDate` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Define a formatting pattern to suit your taste. Or call the `.ofLocalized…` methods to localize automatically.
) // Returns a `String`.
java.time
Date class represents a moment in UTC, a date with a time-of-day, and an offset-from-UTC of zero. Wrong class to use when working with date-only values.
Avoid using the terrible old legacy date-time classes such as Calendar, Date, and SimpleDateFormat. These classes were supplanted years ago by the java.time classes.
Do not track days as a count of seconds or milliseconds. Days are not always 24 hours long, and years are not always 365 days long.
LocalDate
Instead, use LocalDate class.
LocalDate today = LocalDate.now() ;
LocalDate later = today.plusDays( 5 ) ;
Convert
Best to avoid the legacy classes altogether. But if you must interoperate with old code not yet updated to java.time classes, you can convert back-and-forth. Call new methods added to the old classes.
For Date you need to add a time-of-day. I expect you will want to go with the first moment of the day. And I'll assume you want to frame the date as UTC rather than a time zone. We must go through a OffsetDateTime object to add the time-of-day and offset. For the offset, we use the constant ZoneOffset.UTC. Then we extract the more basic Instant class object to convert to a java.util.Date.
OffsetDateTime odt = OffsetDateTime.of( later , LocalTime.MIN , ZoneOffset.UTC ) ; // Combine the date with time-of-day and with an offset-from-UTC.
Instant instant = odt.toInstant() ; // Convert to the more basic `Instant` class, a moment in UTC, always UTC by definition.
java.util.Date d = java.util.Date.from( instant ) ; // Convert from modern class to legacy class.
Going the other direction:
Instant instant = d.toInstant() ; // Convert from legacy class to modern 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.
Use days*86400000L to make this a long calculation otherwise the int value overflows.
Try this one in your code:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 5);
strDate = formatter.format(cal.getTime());

How to convert UTC Date String and remove the T and Z in Java?

Am using Java 1.7.
Trying to convert:
2018-05-23T23:18:31.000Z
into
2018-05-23 23:18:31
DateUtils class:
public class DateUtils {
public static String convertToNewFormat(String dateStr) throws ParseException {
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
sdf.setTimeZone(utc);
Date convertedDate = sdf.parse(dateStr);
return convertedDate.toString();
}
}
When trying to use it:
String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z");
System.out.println(convertedDate);
Get the following exception:
Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7)
What am I possibly doing wrong?
Is there an easier way to do is (e.g. Apache Commons lib)?
tl;dr
Instant.parse( "2018-05-23T23:18:31.000Z" ) // Parse this String in standard ISO 8601 format as a `Instant`, a point on the timeline in UTC. The `Z` means UTC.
.atOffset( ZoneOffset.UTC ) // Change from `Instant` to the more flexible `OffsetDateTime`.
.format( // Generate a String representing the value of this `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) // Specify a formatting pattern as desired.
) // Returns a `String` object.
2018-05-23 23:18:31
ISO 8601
Your input string is in standard ISO 8601 format.
The java.time classes use these standard formats by default when parsing/generating strings.
The T separates the year-month-day portion from the hour-minute-second. The Z is pronounced Zulu and means UTC.
java.time
You are using troublesome old date-time classes that were supplanted years ago by the java.time classes. The Apache DateUtils is also no longer needed, as you will find its functionality in java.time as well.
Parse that input string as a Instant object. 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).
String input = "2018-05-23T23:18:31.000Z" ;
Instant instant = Instant.parse( input ) ;
To generate a string in another format, we need a more flexible object. The Instant class is meant to be a basic building block. Lets convert it to a OffsetDateTime`, using UTC itself as the specified offset-from-UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
Define a formatting pattern to match your desired output.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = odt.format( f ) ;
Tip: Consider using DateTimeFormatter::ofLocalized… methods to automatically localize the String generation per some Locale rather than hard-coding a formatting pattern.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Try this. You have to use one pattern for parsing and another for formatting.
public static String convertToNewFormat(String dateStr) throws ParseException {
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(utc);
Date convertedDate = sourceFormat.parse(dateStr);
return destFormat.format(convertedDate);
}
For others without Java 1.7 Restrictions:
Since Java 1.8 you can do it using LocalDateTime and ZonedDateTime from the package java.time
public static void main(String[] args) {
String sourceDateTime = "2018-05-23T23:18:31.000Z";
DateTimeFormatter sourceFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(sourceDateTime, sourceFormat);
String formatedDateTime = dateTime.atZone(ZoneId.of("UTC")).format(targetFormat);
System.out.println(formatedDateTime);
}
EDIT: (see Comments)
Quote from the Oracle Java documentation of LocalDateTime:
LocalDateTime is an immutable date-time object that represents a
date-time, often viewed as year-month-day-hour-minute-second. Other
date and time fields, such as day-of-year, day-of-week and
week-of-year, can also be accessed. Time is represented to nanosecond
precision. For example, the value "2nd October 2007 at
13:45.30.123456789" can be stored in a LocalDateTime.
This class does not store or represent a time-zone. Instead, it is a
description of the date, as used for birthdays, combined with the
local time as seen on a wall clock. It cannot represent an instant on
the time-line without additional information such as an offset or
time-zone.
the OP is asking to JUST parsing an Input String to a date-time (as year-month-day-hour-minute-second) and the Documentation says
LocalDateTime ... represents a date-time, often viewed as
year-month-day-hour-minute-second
so no important information are lost here. And the part dateTime.atZone(ZoneId.of("UTC")) returns a ZonedDateTime so the ZimeZone is handled at this point again if the user needs to work with the timezone ...etc.
so don't try to force users to use the "One and Only" solution you present in your answer.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.
Also, quoted below is a notice from the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
ZonedDateTime.parse("2018-05-23T23:18:31.000Z")
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH));
ONLINE DEMO
Note that you do not need a custom DateTimeFormatter to parse the date-time string, 2018-05-23T23:18:31.000Z as it is already in the default pattern used by ZonedDateTime. The modern date-time API is based on ISO 8601.
Learn more about the modern Date-Time API from Trail: Date Time.
Some helpful answers using java.time API:
'Z' is not the same as Z.
Never use SimpleDateFormat or DateTimeFormatter without a Locale.
I prefer u to y with a DateTimeFormatter.
For the sake of completeness
For the sake of completeness, given below is a solution using the legacy date-time API:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateTime = parser.parse("2018-05-23T23:18:31.000Z");
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
formatter.setTimeZone(parser.getTimeZone());
String formattedDateTimeString = formatter.format(dateTime);
System.out.println(formattedDateTimeString);
ONLINE DEMO
YYYY does not match with year part. In java 7 you need yyyy.
For T, use 'T' to match it
You're also missing the faction of millsecond part: .SSS
Try this:
String dateStr="2018-05-23T23:18:31.000Z";
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(utc);
Date convertedDate = sdf.parse(dateStr);
convertedDate.toString();
In Kotlin and using ThreeTenABP,
fun getIsoString(year: Int, month: Int, day: Int): String {
val localTime = ZonedDateTime.of(year, month, day, 0, 0, 0, 0, ZoneId.of("Z"))
val utcTime = localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC)
val isoString = utcTime.toInstant().toString() // 1940-15-12T00:00:00Z
val formattedIsoString = val formattedIsoString =
Instant.parse(isoString)
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter
.ofPattern("uuuu-MM-dd'T'HH:mm:ss")) // 'T' in quotes so that it is retained.
return formattedIsoString
}
// print it
print(getIsoString(1940, 15, 12)) // 1940-15-12T00:00:00
You can try this below the idea.
I am not an expert in JAVA but I did it in javascript/node.js
import * as momentTimeZone from 'moment-timezone';
let d = new Data(); // d = '2018-05-23T23:18:31.000Z'; or we can take this date
let finalOutput = momentTimeZone(d).tz(this.locationService.locationTimeZone).utc().format('YYYY-MM-DD HH:mm:ss');
console.log('Result: ', finalOutput); // Result: "2018-05-23 23:18:31";
It also works with moment.js.
Here is more about format.

Getting unable to parse date exception

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.

How to get Date from TimeStamp in java

I am trying to read a timestamp I have in my database mysql and save it to a Date variable in java.
I want it with this format: YYYY-MM-DD HH:MM:SS (24 hour format)
In my database I have a timestamp with that format but each time I try to get as timestamp I read 2014 and if I read it as Date with getDate()... I get "ago 16, 2014"
I'm not sure what you really want. Do you want to get a java.sql.Timestamp instance or do you want to get the timestamp as string with the mentioned pattern?
Maybe that helps:
ResultSet rs = ...
Timestamp t = rs.getTimestamp(...);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(t);
// get the timestamp from the DB
java.sql.Timestamp yourTimestamp = youNameItGetTimestamp();
// Create the corresponding Date object
java.util.Date date = new java.util.Date(yourTimestamp.getTime());
// show in a string
java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
java.lang.String printableDate = formatter.format(date);
System.out.println("here you have it: <" + printableDate + ">");
The other Answers are correct but use troublesome old legacy date-time classes. Instead use java.time classes.
Conversion
New methods have been added to the old classes to facilitate conversion such as java.sql.Timestamp::toInstant().
java.sql.Timestamp ts = myResultSet.getTimestamp( … ) ;
Instant instant = ts.toInstant();
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. Its toString method generates a String in one of the standard ISO 8601 formats.
String output = instant.toString();
2011-12-03T10:15:30Z
You could replace the T with a SPACE and delete the Z to get your format.
output = output.replace( "T" , " ").replace( "Z" , "" ) ;
2011-12-03 10:15:30
ZonedDateTime
If you want to see the same moment but through the lens of a particular time zone, generate a ZonedDateTime.
ZoneId zoneId = ZonedId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
Define a custom DateTimeFormatter object. Or use DateTimeFormatter.ISO_LOCAL_DATE_TIME and replace the T with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );
2011-12-03 05:15:30
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
have you tried some thing like this :
java.sql.Date timeStamp = new java.sql.Timestamp( object.getDate() );
also this link may help you :
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
What's the type of your field? Is it a string/varchar? How about using SimpleDateFormat?
i.e.
final Date myDate = new SimpleDateFormat(FORMAT_STRING).parse(value);
See SimpleDateFormat documentation for more details.
BTW: A litte code and database definition would have been nice...

How to convert current date into string in java?

How do I convert the current date into string in Java?
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
Use a DateFormat implementation; e.g. SimpleDateFormat.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
tl;dr
LocalDate.now()
.toString()
2017-01-23
Better to specify the desired/expected time zone explicitly.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
java.time
The modern way as of Java 8 and later is with the java.time framework.
Specify the time zone, as the date varies around the world at any given moment.
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ; // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;
2017-01-23
By default you get a String in standard ISO 8601 format.
For other formats use the java.time.format.DateTimeFormatter 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, 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.
Faster :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
Most of the answers are/were valid.
The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
You will get a deprecated message for similar calls.
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
The new way of doing this is using the Calendar Instance.
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised.
For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
This is more synonymous to real life
We get a Calendar object and we look for the time in it.
( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic
altogether)
Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters
One more way to do this is using Joda time API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
For time as YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
import org.joda.time.DateTime;
public static Date getDateByString(String dateTime) {
if(dateTime==null || dateTime.isEmpty()) {
return null;
}
else{
String modified = dateTime + ".000+0000";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj = new Date();
Date dateObj1 = new Date();
try {
if (dateTime != null) {
dateObj = formatter.parse(modified);
}
} catch (ParseException e) {
e.printStackTrace();
}
return dateObj;
}
}

Categories

Resources