I have a String as below which needs to be converted into java.sql.Date format:
2017-08-31 01:40:00+00:00
I am using below code and I can see date is only parsed as 2017-08-31 and not the entire string as above. Can someone please suggest?
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(dateTimeStamp);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Based on the suggestion in the answers, I implemented below:
String dateTimeStamp = "2017-08-31 01:40:00+00:00";
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ssZZ");
java.util.Date date = format.parse(dateTimeStamp);
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println("timestamp - " + timestamp);
But, am getting below error:
java.text.ParseException: Unparseable date: "2017-08-31 01:40:00+00:00"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.eneco.mysqlsink.WeatherForecastSink.WeatherForecastTask.put(WeatherForecastTask.java:94)
at org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:435)
at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:251)
at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:180)
at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:148)
at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:146)
at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:190)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
java.sql.Date only provides the date.. You need to use java.sql.Timestamp to get both date and time.
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date date = format.parse("2017-08-31 01:40:00+00:00");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp);
You're using the hh pattern, which corresponds to hour-of-am-pm field (values from 1 to 12). As the input doesn't have AM/PM designator, this won't always work as expected. You must change it to HH (hour-of-day, with values from 0 to 23).
Also, to parse the offset +00:00 you need to use the X pattern:
String input = "2017-08-31 01:40:00+00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
// java.util.Date
Date date = sdf.parse(input);
The X pattern was introduced in Java 7. If you're using an older version, you can also set the UTC timezone in the formatter:
// "X" is not supported
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// set UTC in the formatter
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// java.util.Date
Date date = sdf.parse(input);
This is worse because you need to know the offset from the input and set it in the formatter. So it's better to use X if supported.
Then you can create the sql dates from the java.util.Date:
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
java.sql.Timestamp timestamp = new Timestamp(date.getTime());
But remind that if you just System.out.println the sql date or the timestamp, those will be converted to the JVM default timezone (giving you the impression that it's wrong: see this article for more details).
Also, keep in mind that a java.sql.Date just keeps the date fields (day/month/year), setting the hours to zero (so the 01:40 is lost). A java.sql.Timestamp, on the other hand, preserves the whole UTC millis value.
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java 6 or 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
First you parse the input to an OffsetDateTime, using a DateTimeFormatter to specify the format:
String input = "2017-08-31 01:40:00+00:00";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssXXX");
OffsetDateTime odt = OffsetDateTime.parse(input, fmt);
Then you can convert it to sql types. In Java 8, there are built-in methods to do it:
java.sql.Date sqlDate = java.sql.Date.valueOf(odt.toLocalDate());
java.sql.Timestamp sqlTimestamp = java.sql.Timestamp.from(odt.toInstant());
In Java 7, the ThreeTen Backport has the org.threeten.bp.DateTimeUtils class:
java.sql.Date sqlDate = DateTimeUtils.toSqlDate(odt.toLocalDate());
java.sql.Timestamp sqlTimestamp = DateTimeUtils.toSqlTimestamp(odt.toInstant());
You need to include timezone identifier in your format
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssZZ").parse(dateTimeStamp);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
To get the timestamp just use java.sql.Timestamp instead of java.sql.Date!
The toString() method of the java.sql.Timestamp object should return the string as you needed.
The format you are using is good but you loose Timezone offset.
If you want to consider TimeZone offset then please use below format.
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(dateTimeStamp);
Result:
utilDate = Thu Aug 31 01:40:00 IST 2017
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssX").parse(dateTimeStamp);
Result:
utilDate = Thu Aug 31 07:10:00 IST 2017.
I am running this code from India and there is offset of 05:30 Hours in timezone.
Related
I have a String variable called time is 2016-11-30T00:06:42+05:30
and a duration 32700 i.e 545 minutes.
I want to add duration to above string time stamp and need to calculate start time and end time.
So i want to get StartTime:00:06 and EndTime:09:05.
I tried this but doesn't work
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = sdf.parse(startTime.toString());
Timestamp ts_now = new Timestamp(date.getTime());
System.out.println(">>>>>>"+date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ts_now.getTime());
cal.add(Calendar.SECOND, Integer.parseInt(Value.toString()));
Timestamp later = new Timestamp(cal.getTime().getTime());
System.out.println(">>>>>>"+later);
I tried with X ,Z but got error like
Exception in thread "main" java.text.ParseException: Unparseable date: "2016-11-30T00:06:42+05:30"
at java.text.DateFormat.parse(DateFormat.java:366)
at oneraise.radis.thread.mavenproject1.ParseJson.main(ParseJson.java:48)
I am new to java can anybody help me
Thanks
tl;dr
OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" )
.plus( Duration.ofSeconds( 32_700L ) )
Details
Avoid the troublesome and confusing date-time classes such as java.util.Date and Calendar, now legacy, supplanted by the java.time classes.
Your input string complies with standard ISO 8601 formats. Such strings can be directly parsed by java.time classes with no need to specify a formatting pattern.
Parse as an OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" );
The ZonedDateTime class used in another Answer is inappropriate here. This input string contains only an offset-from-UTC, not a full time zone such as Asia/Kolkata. So OffsetDateTime is the class to use here.
The Duration class handles your span of time, a count of seconds.
Duration d = Duration.ofSeconds( 32_700L );
Add to your date-time object.
OffsetDateTime odtLater = odt.plus( d );
Tip: To view the OffsetDateTime value in UTC, extract an Instant.
Instant instant = odt.toInstant();
Database
For database access, your JDBC 4.2 compliant driver may be able to work with java.time objects via the get/setObject methods.
If so, no need to use the old java.sql.Timestamp class or its siblings.
myPreparedStatement.setObject( … , odt );
If not, use the new conversion methods added to the old date-lime classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( odt.toInstant() );
Here is the format for the string you have given
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
Date date;
try
{
Here I've parsed the string you have given. If you want the current time, use date = new Date();
date = sdf.parse("2016-11-30T00:06:42+05:30");
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Here I've added your interval
cal.add(Calendar.SECOND, 32700);
System.out.println(cal.getTime());
String output = outputFormat.format(date);
System.out.println(output);
String output2 = outputFormat.format(cal.getTime());
System.out.println(output2);
}
catch (ParseException e)
{
e.printStackTrace();
}
Here is the output. I'm in a different timezone.
Tue Nov 29 13:06:42 CST 2016
Tue Nov 29 22:11:42 CST 2016
13:06
22:11
If in your code I change the initialization of the date format to:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
— and I set my computer’s time zone to IST, I get the following output:
>>>>>>Wed Nov 30 00:06:42 IST 2016
>>>>>>2016-11-30 09:11:42.0
Alternatively you may use the Java 8 time classes, but convert to good old Timestamp if this is what you need. Edit: I am thankful to Basil Bourque for correctly pointing out that OffsetDateTime is the class to use, and for the method for converting to timestamp. See his answer for the full explanation.
Instant laterInstant = OffsetDateTime.parse(startTime.toString())
.plusSeconds(Integer.parseInt(value.toString()))
.toInstant();
Timestamp ts = Timestamp.from(laterInstant);
System.out.println(ts);
This prints:
2016-11-30 09:11:42.0
I believe the above does what you want.
I am facing an issue when I convert my string to date format.
This is what I have tried -
First try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
date = df.parse(completionDate1);
System.out.println(date); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
Second try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("yyyy/MM/dd").parse(completionDate1);
System.out.println(completionDate); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
The output I'm expecting is that, the completionDate should be Date format not String. I'm just printing the completionDate just to make sure the date format is getting getting converted.
The main intention of getting it in date format is I need this for an Update query so it has to be Date and not String.
Kindly let me know where I'm going wrong. I need this date format as I need to store this date in a database.
Thanks
You have to format the date after parsing it but your parsing format is also incorrect so its giving wrong output. Try
String completionDate1 = "21/10/2016";
System.out.println(completionDate1);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
date = df.parse(completionDate1);
DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df1.format(date));
DEMO
Wrong pattern
First problem is that your defined parsing pattern does not match your input string. For 21/10/2016 pattern should be dd/MM/yyyy.
java.sql.Date versus java.util.Date
Second problem is that for database access you should be using the java.sql.Date class for a date-only value without time-of-day and without time zone. Not to be confused with java.util.Date which is a date and time-of-day value. You should specify the fully-qualified class name in such discussions as this Question.
Neither of these classes have a “format”. They have their own internal representation, a count from epoch.
java.time
Third problem is that you are using old outdated classes. In Java 8 and later, use java.time framework now built-in. In Java 6 & 7, use its back-port, the ThreeTen-Backport project. For Android, use the adaptation of that back-port, ThreeTenABP.
In the java.time classes we now have the LocalDate class for date-only values.
String input = "21/10/2016"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Hopefully some day JDBC drivers will be updated to directly use the java.time types. Until then, use the new methods added to the old java.sql types to convert.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
Now pass that java.sql.Date object to the setDate method on a PreparedStatement object for transmission to a database.
Note that at no time did we make use of any more strings. We went from original input String to java.time.Date to java.sql.Date.
At no point did we use java.util.Date. Check your import statements to eliminate java.util.Date.
By the way, to go the other direction from java.sql.Date to LocalDate:
LocalDate localDate = mySqlDate.toLocalDate();
Use below code
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("dd/MM/yyyy").parse(completionDate1);
String date = new SimpleDateFormat("yyyy/MM/dd").format(completionDate);
System.out.println(date);
You can try this
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String completionDate = df.format(request.getParameter("completion_date"));
System.out.println(completionDate);
How can I parse a pubDate from a RSS feed to a Date object in java.
The format is: Thu, 03 Mar 2016 15:30:00 +0200
I tried to do it by this:
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
//java.util.Date utilDate = new java.util.Date();
java.util.Date utilDate = new java.util.Date();
try {
utilDate = formatter.parse(date);
}
catch (java.text.ParseException p1)
{
p1.printStackTrace();
}
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
but the java.sql.Date only save the date without the time
for example: "2016-02-06 00:00:00"
java.sql.Date doesn't have Time
You should probably use java.sql.Timestamp
You can use it like this
new java.sql.Timestamp(utilDate.getTime());
RFC 1123
That format of your input string happens to be defined as a standard, RFC 1123.
That format has long been outmoded by the much more sensible formats defined by ISO 8601. If possible I strongly suggest migrating.
java.time
You are using old date-time classes that have been outmoded by the java.time framework built into Java 8 and later.
Your input’s format happens to be predefined as a constant in java.time. So no need to specify a formatting pattern.
String input = "Thu, 03 Mar 2016 15:30:00 +0200";
DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME ;
OffsetDateTime odt = OffsetDateTime.parse( input , formatter );
Someday the JDBC drivers will be updated to use the java.time types directly. Until then convert to the java.sql types, specifically java.sql.Timestamp in our case here. To convert we need an Instant, a moment on the timeline in UTC. We can extract one from our OffsetDateTime.
Instant instant = odt.toInstant();
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.
Possible Solution:Convert Java Date into another Time as Date format
I went through it but does not get my answer.
I have a string "2013-07-17T03:58:00.000Z" and I want to convert it into date of the same form which we get while making a new Date().Date d=new Date();
The time should be in IST Zone - Asia/Kolkata
Thus the date for the string above should be
Wed Jul 17 12:05:16 IST 2013 //Whatever Time as per Indian Standard GMT+0530
String s="2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
TimeZone tx=TimeZone.getTimeZone("Asia/Kolkata");
formatter.setTimeZone(tx);
d= (Date)formatter.parse(s);
Use calendar for timezones.
TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
Calendar cal = Calendar.getInstance(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2013-07-17T03:58:00.000Z"));
Date date = cal.getTime();
For this however I'd recommend Joda Time as it has better functions for this situation. For JodaTime you can do something like this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime dt = dtf.parseDateTime("2013-07-17T03:58:00.000Z");
Date date = dt.toDate();
A Date doesn't have any time zone. If you want to know what the string representation of the date is in the indian time zone, then use another SimpleDateFormat, with its timezone set to Indian Standard, and format the date with this new SimpleDateFormat.
EDIT: code sample:
String s = "2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date d = formatter.parse(s);
System.out.println("Formatted Date in current time zone = " + formatter.format(d));
TimeZone tx=TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tx);
System.out.println("Formatted date in IST = " + formatter.format(d));
Output (current time zone is Paris - GMT+2):
Formatted Date in current time zone = 2013-07-17T05:58:00.000+02
Formatted date in IST = 2013-07-17T09:28:00.000+05
java.time
I should like to provide the modern answer. And give you a suggestion: rather than reproducing what Date.toString() would have given you, better to use the built-in format for users in the relevant locale:
String isoString = "2013-07-17T03:58:00.000Z";
String humanReadable = Instant.parse(isoString)
.atZone(userTimeZone)
.format(localizedFormatter);
System.out.println(humanReadable);
On my computer this prints
17 July 2013 at 09.28.00 IST
My snippet uses a couple of constants
private static final ZoneId userTimeZone = ZoneId.of("Asia/Kolkata");
private static final DateTimeFormatter localizedFormatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.getDefault(Locale.Category.FORMAT));
The withLocale call is redundant when we just pass the default format locale. I put it in so you have a place to provide an explicit locale, should your users require a different one. It also has the nice advantage of making explicit that the result depends on locale, in case someone reading your code didn’t think of that.
I am using java.time, the modern Java date and time API. It is so much nicer to work with than the outdated Date, TimeZone and the notoriously troublesome DateFormat and SimpleDateFormat. Your string conforms to the ISO 8601 standard, a format that the modern classes parse as their default, that is, without any explicit formatter.
Same format as Date gave you
Of course you can have the same format as the old-fashioned Date would have given you if you so require. Just substitute the formatter above with this one:
private static final DateTimeFormatter asUtilDateFormatter
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
Now we get:
Wed Jul 17 09:28:00 IST 2013
Link to tutorial
Read more about using java.time in the Oracle tutorial and/or find other resources out there.