I'm trying to obtain the difference between two dates but i'm stuck at converting a string into a date.
My code is:
//create a date send it to the database as string
Date currentDate = new Date(); // date looks like: Sat Sep 01 10:20:14 EEST 2012
SaveToDB(currentDate.ToString());
At some point i;m trying to retrieve the date from the database:
String dateStringFromDb = GetDateFromDB(); //Sat Sep 01 10:20:14 EEST 2012
Date currentDate = new Date();
//now i'm trying to covnert the dateStringFromDb into a Date, this throws an exception
Date dbDate = DateFormat.getInstance().parse(dateStringFromDb); //this throws exception
long difference = currentDate.getTime() - dbDate.getTime(); // does this give me the correct difference in GMT even if timezones for the two dates are different?
Can you please point me to the correct solution?
Unfortunately the date from the database is retrieved as a String and i can't change that to another type. So i need to convert that string into Date().
EDIT:
Exception is :
java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at main.Program.main(Program.java:20)
I would suggest using Joda Time API for your data and time related operation in Java. Handling timezone and all related conversion nuances are pretty easy using this API.
You should specify a DateFormat to match the string format being received
Eg.
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));
Once you have the both the dates in required format, then apply the date arithmetic operations
Other Format Specifiers for DateString can be found in
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Related
I've got Timestamp format in DB and my setEventDate method needs Date format.
So in my DAO class there is something like this :
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Timestamp dbDate = rows.getTimestamp("event_date");
String dbDateToString = new SimpleDateFormat("HH:mm").format(dbDate);
Date dbDateToDate = sdf.parse(dbDateToString);
e.setEventDate(dbDateToDate);
System.out.println(dbDateToString);
System.out.println(dbDateToDate);
I'm getting Timestamp from DB, format it to String and in next step I'm parsing it to Date. I know that it sounds weird. The result is:
String - 17:08
Date - Thu Jan 01 17:08:00 CET 1970
I don't get it :/ I need that "HH:mm" format.
You are taking a Timestamp from your DB, you need to change it a Date first
Timestamp dbDate = rows.getTimestamp("event_date");
Date d = new Date(dbDate.getTime();
now you can do your SimpleDateFormat formatting stuff
Timestamp dbDate = rows.getTimestamp("event_date");
Date d = new Date(dbDate.getTime());
String dbDateOnlyHourAndMinutes = new SimpleDateFormat("HH:mm").format(dbDate);
there you have your Hour and minutes only "Date".
You say you want to parse date but in your date format you are passing only hours (HH) and minutes (mm) format.
Check how to create your desired date format from :
What are the date formats available in SimpleDateFormat class?
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
example of a date format is: dd/MM/yyyy.
In case i did not understood correctly please explain more.
Here is an example code to convert the timestamp to your format.
ASSUMPTION: desired date format is MM:yyyy:
Timestamp stamp = new Timestamp(System.currentTimeMillis());//your timestamp goes here
Date date = new Date(stamp.getTime());
System.out.println(date);//result = Tue Mar 27 18:50:09 EEST 2018
SimpleDateFormat sdf = new SimpleDateFormat("MM:yyyy");
System.out.println(sdf.format(date)); //result = 03:2018
my problem is the following. I would like to have the german date for the string "11.11.2012".
I tried this piece of code:
String date = "11.11.2012";
SimpleDateFormat sdtF = new SimpleDateFormat("dd.mm.yyyy",Locale.GERMANY);
Date dareFormatiert = sdtF.parse(date);
System.out.println(dareFormatiert);
But it gives me the wrong format. "Wed Jan 11 00:11:00 CET 2012", instead of "11.11.2012".
Thank you, any help is appreciated.
You have to use M in you pattern, because M is the month and m is the minute!
String date = "11.11.2012";
SimpleDateFormat sdtF = new SimpleDateFormat("dd.MM.yyyy",Locale.GERMANY);
^^^^
Date dareFormatiert = sdtF.parse(date);
System.out.println(dareFormatiert);
For more information see the documentation of SimpleDateFormat
but i still have the same output: Sun Nov 11 00:00:00 CET 2012
Try to understand the thing when you use
SimpleDateDFormat#parse() - It parses text from a string to produce a Date.
and Date object in java always contains date along the time.
Javadoc says Date() - Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
and FYI Sun Nov 11 00:00:00 CET 2012 is equal to 11.11.2012
Edit: try this
public static Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null && !(date.equals(""))) {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
return sqlDate;
}
return null;
}
pass the util date you got above and this method shall return the sql format date then store the sqlformat date in mysql column-field of type Date
This question already has answers here:
Is java.util.Date using TimeZone?
(5 answers)
Closed 7 years ago.
String = 26/8/2013 15:59;
I want to convert this date into GMT, however after applying the below code, I get the EEST time rather than the GMT.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy h:m");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse(newDate);
Log.i(tag, df.parse(newDate).toString());
Output :
Mon Aug 26 18:59:00 EEST 2013
Whats wrong ?
Your parsing is correct, the different is just for your locale time zone that is used to display when you are making toString(). I just used formatted output to demonstrate the correct format . Here is the details example:
final String time = "26/8/2013 15:59";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(time);
// localDate.toString()
// PRINT. Mon Aug 26 15:59:00 EEST 2013
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
// PRINT. 26/08/2013 12:59
Nothing's really wrong. You are successfully parsing the datetime string interpreted as UTC timezone.
When printing it to log, you get what you ask for - Date.toString() returns the date formatted to current locale settings which include the timezone. The difference between UTC and EEST is 3 hours.
If you want to to format it to display some other timezone, pass it though format() of a SimpleDateFormat that is configured to the timezone you want.
I think you should use the below approach:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);
This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.
Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.
One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));
If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy
I am using Jackrabbit to store my documents.
Now I would like to search for documents that were created e.g. after a specific date using XPATH. To do so, I tried something like:
String dateString = date.toString();
//element(*,nt:file)[#jcr:created >= xs:dateTime(dateString)]
date is an object of class java.util.Date
dateString gets formatted as: Wed Mar 16 00:00:00 CET 2011
But this is giving me an InvalidQueryException, indicating that the dateString is wrong:
Invalid query: Lexical error at line
1, column 136. Encountered: "0" (48),
after : ":" for statement
So the question is: What is the correct format of a date for xs:dateTime ?
Thanks in advance
For Jackrabbit this worked for me:yyyy-MM-dd'T'HH:mm:ss.SSSX
(2015-12-16T15:16:50.465-02:00) when some previous code had taken a Calendar and done:prop.getValue().getString()
Couldn't get Z to work ("Unparseable date").
Just for the sake of completeness:
I found another (Jackrabbit/JCR dependend) way to get a correctly formatted date string:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String dateString = ValueFactoryImpl.getInstance().createValue(cal).getString();
This dateString can be used with the single arg constructor of xs:dateTime
xs:dateTime uses a specific pattern - see here and here. So instead of using date.toString(), to produce that format, you would need to use a suitable DateFormat. Something like this:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String dateString = format.format(date);
However, it appears that the constructor for xs:dateTime in fact requires two args: one for date and one for time. See here.
So I would guess you could use this:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat tf = new SimpleDateFormat("HH:mm:ss");
String dateString = df.format(date);
String timeString = tf.format(date);
Also I have some problems with JAckRabbit date format and I needed to get some entities between two dates :
#createdDate >= xs:dateTime(startDate)
#createdDate <= xs:dateTime(endDate)
What I noticed is :
using format yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to parse the date gave incorrect results( also it should be yyyy-MM-dd'T'HH:mm:ss.SSSZ) but you get for example :
2012-01-04T23:59:59.999+0200 instead of
2012-01-04T23:59:59.999+02:00 (saved in JCR)
Solution with ValueFactoryImpl.getInstance().createValue(cal).getString() works.