Java - SimpleDateFormat unexpected parsing behaviour - java

I'm reading information from a file (.csv) that will be inserted to a database after validation and approval from the end user. The text file is read, validated and its information loaded to a List containing forms which are used to check if the data already exist in database.
The problem arises when parsing the String to Date. The SimpleDateFormat.parse() method returns an unexpected date format even when the pattern for SimpleDateFormat is "yyyy-MM-dd".
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
Parsing the loaded values to the travel object:
travel.setDate( dateFormat.parse( form.getTravelDate() ));
In debugger the form shows the date as:
"2012-12-12"
It is read as intended. However when parsed becomes:
Wed Dec 12 00:00:00 CST 2012
I've spent the whole day trying to solve this but I'm out of ideas at this point. Afaik the pattern is alright and I've tried adding a locale to no avail.
Edit: the problem is when I need to insert the values to the database using Hibernate. The not desired format also ends up showing in the Database.
The data is show in a .jsp page using
HttpServletRequest("table",travelList);
The date format I don't need shows here, when in the past this issue never happened. At last the information is sent to the database where the problem persists.

No, it "becomes" a java.util.Date value. If you're then converting it back to a string by calling Date.toString(), you should consult the Date.toString() documentation for what to expect.
The value stored in the Date is just a point in time - the number of milliseconds since the Unix epoch. There's no format in there, no time zone etc. It also doesn't know that it was only a date value rather than a date and time (the naming of Date is one of the many unfortunate aspects of the API).
It's crucial that you mentally separate "the result of the parse operation" from "the string value that is used to represent that result if I call toString"".
I'd also advise you to set the time zone on your SimpleDateFormat to UTC when parsing a date - that way you know that you can't possibly have any ambiguous or skipped times leading to hard-to-predict behaviour. (Of course, you then need to know that you'll have parsed the date to "the start of the UTC date" and handle it appropriately elsewhere.)

You need to use the formatter when printing the Date as well.
dateFormat.format( travel.getDate() );
When your parse the String using a DateFormat, you get a complete Date object with the time units missing in the string initialized to zero. In your example, that's hours, minutes and seconds.
By default, if you do not use a formatter, Date's default string representation (provided by its toString() method) gets printed.

Parsing doesn't mean it format, it simply parse it as text to a java.util.Date object. See parse method in documentation.
You need to use the format method.
dateFormat.format(travel.getDate())
See documentation for more details.

if form.getTravelDate() is returning String then First Parse the Date from String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
Date parsedDate=dateFormat.parse(form.getTravelDate());
// Here parsedDate is in form Wed Dec 12 00:00:00 CST 2012
Now Format the Date using the Same SImpleDateFormat to get the desired output
System.out.println(dateFormat.format(parsedDate));
Your Desired Output
2012-12-12
Update
Assuming data Type of Columns in which we insert this data in Database is of Date Type not varchar then use the below statement
travel.setDate(dateFormat.format(parsedDate));

As I understand parse method returns Date. Below is the parse method syntax.
public Date parse(String source)
throws ParseException
So, you need to parse the string date and store into a Date variable. Then format the Date variable using SimpleDateFormat.
//getTravelDate is "2012-12-12"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
Date dtObj=new Date();
dtObj=dateFormat.parse(form.getTravelDate()); //Store in date variable
System.out.println(dateFormat.format(dtObj)); // Now format the date object
The final output will be 2012-12-12. Hope it will help you.

Related

How do I edit a Date to display in a different format?

I am storing datetime as text in the format dd-MM-yyyy hh:mm:ss in SQLite database. I want to convert it to a date object in the same format. I'm only able to convert it to the format Mon Jun 16 01:35:38 GMT+05:30. How can I have it as a Date object of the required format? Here TSArray[] contains the dates in string format:
int dateArraySize=TSArray.length;
Date dateArray[]=new Date[TSArray.length];
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
for (int i=0;i<TSArray.length;i++) {
try {
//converting String date to Date
Date result=df.parse(TSArray[i]);
dateArray[i]= result;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date objects in Java simply represent an instant in time (specifically, the number of milliseconds before or after the epoch) - they don't store any information about how they should be displayed, nor should they. Formatting a date is purely for display purposes, and is the concern of the DateFormat hierarchy of classes and shouldn't be done until display time (unless you have a compelling reason to do it earlier than that, but I can't think of a good one).
There's arguably nothing to stop you sending a DateFormat object alongside your Date, but you should never need to if you properly internationalise your code in the first place.
One reason that you shouldn't do this is down to the difference in regional date formats. If you presented me with the date 03/07/2014, I'd see that as the 3rd of July 2014, because here in the UK we format our dates as DD/MM/YYYY. Present the same date to someone in the USA and they'll see it as March the 7th 2014, because US dates are typically MM/DD/YYYY.
The database and the server don't need to know any locale information about the client, they should simply serve the requests for data where appropriate and let the client (which does know the locale information) format that data appropriately.
TL;DR:
You can't, because Java Date objects don't store display formatting rules.
As you're using AChartEngine you should be able to achieve what you're after by using a TimeChart and passing in the date format mask via a call to the chart's setDateFormat(String) method.
Database return value in java.sql.date n java default you are using java.util.date. Java.util.date convert into java.sql.Date like below given..
Calendar cal = Calendar.getInstance();
Java.sql.Date sqlDate = new java.sql.Date(cal.getTimeInMillis());

Java & MySQL timezone issue

I am trying to convert a string date value in java to date and trying to store it in a mysql table.
Below the code snippet:
DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String string = "07/24/2013 17:57:52 UTC";
Date a = dfm.parse(string);
System.out.println(a);
My problem is that the above code always returns the following console output:
Wed Jul 24 17:57:52 PDT 2013
I don't know why the time zone is getting changed, more over when I am trying to put this into the database then it is storing it in '2013-07-24 17:57:52' format. I am not sure why the above code is returning me timezone in PDT?
Can you guys please explain me that? My intent is to store a UTC date which will come as an input and store it into the MySQL timestamp field.
Thanks in Advance.
Right, if you can fix the string to not include the time zone, it's simpler. Firstly, you need to understand that a Date object doesn't contain a time zone at all - it's just a point in time.
Next, as we're trying to parse a date/time specified in UTC, you should set that in the SimpleDateFormat:
DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone("UTC"));
Now at that point I'd hope that JPA would do the right thing. You'd at least be passing the right value to the Timestamp constructor.
However, this part of the MySQL documentation makes me nervous:
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
It sounds like you may want to use a DATETIME field instead, to stop this time zone conversion. Setting the time zone of the connection to UTC would help when storing it, but you'd still need to worry about what would happen when fetching. (Databases are pretty messed up when it comes to date/time types, IMO. This is just another example of that...) On the other hand, if you're fetching the data back with Java as well, I'd hope that it would just work transparently. It's probably worth at least trying that...
You are missing the timezone part in your format string. "UTC" is therefore ignored.
Try this:
DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); // added "z"
// then the rest of your code as-is
String string = "07/24/2013 17:57:52 UTC";
Date a = dfm.parse(string);
System.out.println(a); // prints "Wed Jul 24 19:57:52 CEST 2013" for me
Further to #JonSkeet 's word of warning, MySQL "current time zone" can be checked or changed through the time_zone session variable.
Either make sure your session is set to UTC (SET time_zone = '+0:00'), or use a DATETIME type instead.

How to getDate with yyyy-MM-dd format

How can I get the current date of the system with this format yyyy-MM-dd
I want this
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String strDate = formatDate.format(now);
return strDate;
but returning a Date instead of a String.
Any help is greatly appreciated.
UPDATE: If that's the case, can I parse my String to Date?
How can i get the current date of the system with this format yyyy-MM-dd but returns Date instead of String.
You can't. There's no such thing as "a Date with a format" any more than there's the concept of "an int with a format". A Date value is just a point in time, with no associated text format, calendar system or time zone.
Using new Date() will get you a Date object representing the current instant in time, and nothing else. How you use that is up to you - but if you return it from a method then there is no associated date (as the date will vary by time zone), no format etc - it's up to the calling code to use it appropriately.
You might want to consider using Joda Time which at least has a LocalDate type - although you still need to consider which time zone you want to use when you think about "the current date". (And there's still no formatting information associated with the value.)
EDIT: To answer your update, you can just use SimpleDateFormat to parse - but it's not clear where your string has come from to start with. This sounds like the opposite requirement from the rest of your question.
since you cant change Date format build your own CustomDate, it is just a representation of time.
on the method which recieves the date as a string
use another simpledateformatter
and convert the string into date by using
simpledateformatter.parse(strDate);
You can use this .!!
String formatDate = new SimpleDateFormat("yyyy-MM-dd").format( yourDate);

How to show date and time from milliseconds in Android?

I want to display the date of a trip. In the application several trips are listed, each has a long value with the currentTimeMillis of its generation. I want to turn this long number into a date but the output is always something around 1970... Is System.currentTimeMillis() the right way to store the time of the trip generation?
Date date = new Date(trip.getStartTime()); // 195342322
SimpleDateFormat test = new SimpleDateFormat("yyyy-MM-dd");
startTime.setText(String.valueOf(test.format(date)));
-> Output of startTime: 1970-01-01
Try to use Calendar for simple formatting
We don't know how trip.getStartTime() is implemented, however it returns a wrong value. 195342322 is Wed, 10 Mar 1976 21:45:22 GMT (you can check it online)
Since the only non-deprecated Date constructor accepts a long argument, I guess you used that. It's better to store the date(time) in a database-friendly way, such as ISO 8601. Note that if you store it on the client in a SQLite database, SQLite doesn't have a time type, and you have to use a text field for that.
Once you switch to the text representation for serialization, you will be able to get back a Date by using SimpleDateFormat.parse()
use something like this:
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(trip.getStartTime());
Date date =calendar.getTime ();
as shown here .

can we get the pattern of the given date object

How to get the pattern of the given date object
I am getting one Date object as a parameter in my method and I want to know the pattern of the date to convert it into user selected timezone.
You've misunderstood what a Date means. It's just a number of milliseconds since the Unix epoch. It has no concept of time zone, calendar or text format. If it helps, think of it as being a bit like int - an int isn't in hex, decimal or binary - it's just a number within a certain range. If you parse "1a" as hex, that gives an indistinguishable result from parsing "26" as decimal. The same goes for Date.
Of course, this was already explained in comments to some extent, but your reply of:
ok, but while i getting the date object which already set a format i want to know that format.
... suggests you didn't really understood it. The concept of "which already set a format" makes no sense in the context of a Date.
If you need a particular format to be applied, you should pass the DateFormat along as well as the Date.
You can't from the date object itself however (depending on your exact requirements) you could use
DateFormat.getDateTimeInstance()
Which will return to you the default style and format for the locale however like I said that's dependant on your requirement...
The alternative is change your method signature to accept the format as well.
You should create DateFormat. Date knows nothing about TimeZone.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
// Set TimeZone
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(formatter.format(date));
// Change timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(formatter.format(date));

Categories

Resources