I am doing something like this in my program :
Calendar cal = DatatypeConverter.parseDateTime("2012-05-29T11:17:04.805-07:00");
System.out.println(cal.getTime().toString());
o/p:
Tue May 29 13:17:04 CDT 2012
Why is the result showing time of 13:17:04, in the input I have given 11:17:04 and time zone -07:00 which is pacific time zone. Should it not print out 11:17:04 ?
Your timezone - the default one when the program is running is different from the timezone given to the DatatypeConverter.parseDateTime() method and the cal.getTime().toString() method used the default timezone to format the date.
Never use Date.toString() to format Date - a Date only knows the milliseconds from the Epoch time. Instead use java.text.SimpleDateFormat like this:
SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(dateObject).
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
import javax.xml.bind.DatatypeConverter;
class TestDate
{
public static void main(String[] args)
{
Calendar cal = DatatypeConverter.parseDateTime("2012-05-29T11:17:04.805-07:00");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
df.setTimeZone(TimeZone.getTimeZone("GMT-07:00"));
String date = df.format(cal.getTime());
System.out.println(date);
}
}
Related
how to convert date from "Tue May 08 2018 13:15:00" to "2018-05-08 13:15:00.000" in java, As i have to use it for where clause in custom sql query ex- TO_timestamp('2018-05-08 13:15:00.000', 'YYYY-MM-DD HH24:MI:SS.FF')
I think I have a suggestion to try to resolve your problem...
Note: You may have to configure the Locale of the SimpleDateFormat because of the translation of dates in the String. Otherwise the exception java.text.ParseException will be thrown.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
try {
String dateStr = "Tue May 08 2018 13:15:00";
SimpleDateFormat sdfBefore = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat sdfAfter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdfBefore.parse(dateStr);
System.out.println(sdfAfter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I hope I've helped.
First you need to parse your string:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEE MMM dd uuuu H:mm:ss", Locale.ENGLISH);
String dateTimeString = "Tue May 08 2018 13:15:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime);
This prints
2018-05-08T13:15
As has been said in the comments, don’t transfer a string to your database. Assuming you are using at least Java 8 and at least JDBC 4.2 just give the parsed LocalDateTime object to the database through your PreparedStatement, for example:
PreparedStatement queryStatement = yourDbConnection.prepareStatement(
"select * from your_table where your_column = ?");
queryStatement.setObject(1, dateTime);
I am assuming that the source of your string and your database agree about in which time zone the date and time should be interpreted. For most purposes you should prefer to be explicit about time zone.
For anyone reading along and needing a string like 2018-05-08 13:15:00.000 for some other purpose than a database query, the way to obtain this format is through one more formatter:
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String formattedDateTimeString = dateTime.format(targetFormatter);
System.out.println(formattedDateTimeString);
This prints
2018-05-08 13:15:00.000
Link: The Java™ Tutorials: Trail: Date Time explaining how to use java.time, the modern Java date and time API.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
String dateStr = "Tue May 08 2018 13:15:00";
DateTimeFormatter formatterFrom = DateTimeFormatter.ofPattern("EEE MMM dd yyyy HH:mm:ss");
LocalDateTime localDate = LocalDateTime.parse(dateStr, formatterFrom);
DateTimeFormatter formatterTo = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String localDate1 = formatterTo.format(localDate);
System.out.println(localDate1); // 2018-05-08 13:15:00.000
}
}
The problem is pretty simple, I have a TimerTask that is going to be scheduled daily or weekly. (Depends on the given start date and period in config file).
So in config file I specify the day of week and time of execution with period between executions. But Joda-Time refuses to work with my date :(
Here is basic input:
String input = "Tue 12:00:00";
DateTimeFormatter formatter = DateTimeFormat.forPattern("EEE HH:mm:ss");
DateTime dateTime = DateTime.parse(input, formatter); // Here parse exception is thrown...
Exception message: java.lang.IllegalArgumentException: Invalid format: "Tue 12:00:00"
Could someone explain me why I cannot parse this date like that and maybe point me into right direction to solve this kind of problem. Of course I could manually parse the date and set things in calendar, but I don't want to reinvent the wheel if there is something like Joda-Time that could do it for me.
The weekday text Tue probably doesnt match that of your default locale.
DateTimeFormatter formatter =
DateTimeFormat.forPattern("EEE HH:mm:ss").withLocale(Locale.ENGLISH);
You can use Locale. The following code is working fine.
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Test22 {
public static void main(String[] args) {
// TODO Auto-generated method stub
DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE HH:mm:ss").withLocale(Locale.ENGLISH);
String formatedDate = dtf.print(currentDate);
System.out.println(formatedDate);
DateTime now = dtf.parseDateTime(formatedDate);
System.out.println(now);
}
}
Output:
Thu 23:36:33
2000-12-28T23:36:33.000+06:00
Resource Link: https://stackoverflow.com/a/41465180/2293534
The below gives: 1475020875000. When I convert this epoch back to a human readable timestamp, I get: Wed, 28 Sep 2016 00:01:15 GMT, which is different from the initial date?
String date = "2016-09-27 20:01:15.0";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
You should specify Timezone for both input and output. You can use "z" to instantiate SimpleDateFormat and setTimeZone before using format method:
package stackoverflow;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Programa {
public static void main(String[] args) throws ParseException {
String date = "2016-09-27 20:01:15 GMT";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
Date d = new Date(epoch);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String out = df.format(d);
System.out.println(out);
}
}
For available Timezones, try TimeZone.getAvailableIDs()
Worked fine here:
package stackoverflow;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Programa {
public static void main(String[] args) throws ParseException {
String date = "2016-09-27 20:01:15.0";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
Date d = new Date(epoch);
String out = df.format(d);
System.out.println(out);
}
}
You certainly forgot to consider the Timezone to use. If you do not define it, the default (from the JVM) is taken, and can for example differ depending on your server.
Try LocalDateTime
String date = "2016-09-27 20:01:15";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
LocalDateTime ld = LocalDateTime.parse(date, formatter);
long epoch2 = ld.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(epoch2);
Instant in = Instant.ofEpochMilli(epoch2);
LocalDateTime ldt = LocalDateTime.ofInstant(in, ZoneId.systemDefault());
System.out.println(ldt);
output
1474986675000
1474986675000
2016-09-27T20:01:15
I am having a problem using the parseDateTime method in joda time. When I try to parse the date below, the result is one day off. I know there is already a similar thread about this, and I know that if your dayOfWeek and dayOfMonth are mismatched, it prioritizes the dayOfWeek. But my date is valid -- I have checked that february 22 falls on a Friday. But when I parse it, I am getting thursday, february 21. Here is the code:
DateTimeFormatter NBSfmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z");
DateTimeFormatter MYfmt = DateTimeFormat.forPattern("yyyy-MM-dd");
String date ="Fri, 22 Feb 2013 00:00:00 +0000";
DateTime datetime = NBSfmt.parseDateTime(date);
System.out.println(datetime.toString());
And here is the output:
2013-02-21T19:00:00.000-05:00
Anyone have any idea what is going on here? Any insight would be greatly appreciated.
Thanks,
Paul
This is caused by your timezone. You define it in +0000 but then you're viewing it in -05:00. That makes it appear one day before. If you normalize it to UTC, it should be the same.
Try this code, as evidence:
package com.sandbox;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Sandbox {
public static void main(String[] args) {
DateTimeFormatter NBSfmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z");
String date = "Fri, 22 Feb 2013 00:00:00 -0500";
DateTime datetime = NBSfmt.parseDateTime(date);
System.out.println(datetime.toString());
}
}
For you, this should show the "right day". But for me, it shows 2013-02-21T21:00:00.000-08:00 because I'm in a different timezone than you. The same situation is happening to you in your original code.
Here's how you can print the string out in UTC:
package com.sandbox;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Sandbox {
public static void main(String[] args) {
DateTimeFormatter NBSfmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z");
String date = "Fri, 22 Feb 2013 00:00:00 +0000";
DateTime datetime = NBSfmt.parseDateTime(date);
System.out.println(datetime.toDateTime(DateTimeZone.UTC).toString());
}
}
This prints 2013-02-22T00:00:00.000Z.
The timezone of yours is -5, and joda treats the input as UTC in the example. You can use withZone to get a new formatter if needed.
I have a website which supplies date in 2 formats: 28th June 2009 or June 2009.
Now I would like to convert both of these into the same format yyyy-mm-dd hh:mm:ss using MySQL and Java.
SimpleDateFormat gives an error: "Unparsable Date". What's the solution?
What about June 2009 as you can not say its a date you need to make it a date by adding a day in this month-year format. Ex.. add first day of month here and make it 1 June 2009 then parse it in desired format.
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) throws IOException, ParseException
{
String dateStr = "28 June 2009";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(new Date(dateStr)));
}
}