Date format return wrong date - java

I'm trying to format a Date object and convert that formatted one back to Date type object
This is my code
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz");
System.out.println("before format "+invoiceDate);
invoiceDate=inputDf.parse(inputDf.format(invoiceDate));
System.out.println("after format "+inputDf.format(invoiceDate));
System.out.println("after parse "+invoiceDate);
Out put from above code is
before format : Mon Jan 14 10:55:40 IST 2013
after format : Mon Jan 14 2013 10:55:40 IST
after parse : Mon Jan 14 10:55:40 IST 2013
You can see here after i parse the date object it converting back to original format(format which shows before format) but i want Date object like it appear in second print line(after format) thing is .format method returns String not a Date object, how can i fix this ?
Thanks

The Date object doesn't define any format. Date is just a long number with time in it.
In order to modify its format you have to use a String object, as you did in your example.
If you analyze your example:
before format: Shows the DEFAULT format for a Date that System.out.println offers.
after format: Shows the format given after using the SimpleDateFormat.
after parse: We are again in the first case.

This behaviour is because the SimpleDateFomat does not impose itself upon the date. The SimpleDateFormat is merely a pattern to get a formated output out of any Date, but it does not change the date itself. Date does not have a format, so
System.out.println("before format "+invoiceDate);
defaults to the default pattern format.
Actually, the SimpleDateFormat is exactly the way to achieve what you want, ie use it to properly format your output everytime you need it. Formating a date object gives you a representation of it, a String.

System.out.println("after parse "+invoiceDate);
Here you just trying to print the Date object . The Date object , per se, doesn't have any format. The class Date represents a specific instant in time, with millisecond precision. Hence we use DateFormat to format the output string which is printed on printing the Date object . To display the same output as second statement , you need to format it again.
System.out.println("after parse"+inputDf.format(invoiceDate));
Look at the Javadoc for implementation of the toString() for Date :
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy

Related

preventing the use of SimpleDateFormatter twice

I had a String in this form, EEE, dd MMM yy hh:mm:ss Z and I wanted to convert it into the Date object so i did this,
SimpleDateFormat fDate = new SimpleDateFormat("EEE, dd MMM yy hh:mm:ss Z",Locale.getDefault());
then I created the instance field of type Date
Date toDate = null;
and parse my String date and store it into toDate
toDate = fDate.parse(stringDate);
Now the date is stored in toDate variable in this form,
Tue Jan 20 07:33:06 GMT+05:30 2015
but this is not what i wanted.
I wanted my final Date object in this form,
Tue Jan 20, 2015
So, in order to achieve this, I created the new Calendar object and set its time to toDate,
Calendar s = Calendar.getInstance();
s.setTime(toDate);
then I create a new String and store Day of Week, Month Day of Month and year to get this format Tue Jan 20, 2015.
String newDate = s.getDisplayName(Calendar.DAY_OF_WEEK,0,Locale.getDefault()) + " "
+ s.getDisplayName(Calendar.MONTH, 0, Locale.getDefault())
+ " " + s.get(Calendar.DAY_OF_MONTH) + ","
+ s.get(Calendar.YEAR);
Now, my new string newDate has a date in this form Tue Jan 20, 2015 and the problem is it is a String object and not a Date object, and in order to convert it to Date object I have to use the SimpleDateFormatter again.
But this is a lot of work because in order to convert String of this form, EEE, dd MMM yy hh:mm:ss Z into the Date object of this form, Tue Jan 20, 2015, I am first using SimpleDateFormatter then I am parsing it in a Date object, then I extract my desire fields from that Date object using Calendar and store in a String, and then convert that String back to the Date object.
Is there any easier way to achieve this ? i.e, converting this String EEE, dd MMM yy hh:mm:ss Z directly into this format Tue Jan 20, 2015 of type Date without using SimpleDateFormatter twice ?
While the Java Date library is notoriously bad (which is pretty much why everyone uses the Joda-Time library, and why Oracle released the new java.time package with Java 8 (see article), there are a couple things to be aware of:
ALL java.util.Date represents is the number of milliseconds since midnight, Jan 1, 1970 in UTC. In other words, java.util.Date is really just a small wrapper around a long value.
Thus, java.util.Date does NOT store any kind of formatting info. Date.toString() just always produces a String in a human readable "debug" format.
To answer your question, no, there is really not a way to prevent the use of SimpleDateFormatter twice, but I don't see why you would want to avoid this, besides that it seems like you are misunderstanding the concepts of what a Date represents. If you have a java.lang.String and want to convert it to a java.util.Date, you use DateFormat.parse(), and if you have a java.util.Date and want to convert it to a java.lang.String, you use DateFormat.format().

TimeZone Conversion with SimpleDateFormat in Java

I have a SimpleDateFormat parser that parse in this way:
sdf = new java.text.SimpleDateFormat("yyyy-MM-DD HH:mm:ss z").parse("2013-10-25 17:35:14 EDT");
log.debug(sdf);
This give me Sat Jan 26 03:05:14 IST 2013
What am i missing here?
First of all, DD stands for day in year, You should use dd instead.
Also, if you want to print a date in a specific format, you need to use two SimpleDateFormats.
SimpleDateFormat.parse returns a Date object represents the date you specified at the given format.
The Date object itself is saved as a regular Date, no format attached to it.
If you want to print it in a specific format, you need to use another SimpleDateFormat and call format method.
you should use Format
SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:SS z");
String sdf = sdf1.format(sdf1.parse("2013-10-25 17:35:14 EDT"));
There are two things.
sdf is an object of Date, which represents a specific instant in time (milliseconds elapsed since another instant known as "the epoch"). There is no format which is known to this object. And how this object is printed is solely handled by its class' toString method, which prints the date in this format:
dow mon dd hh:mm:ss zzz yyyy
This is exactly what you see in your output. Note that the timezone of the machine running the program is printed in this case. If you wish to print this object in a format of your choice you should use a DateFormat. To get output for a specific timezone you have to explicitly tell it to the DateFormat object (see below).
Another thing is you should be using dd instead of DD in the pattern. D is for day in year and d is for day in month, which I believe is what you want. Now keeping in mind both the points, this is one of the solutions to your problem:
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("EDT")); // Time Zone for output
Date d = sdf.parse("2013-10-25 17:35:14 EDT");
System.out.println(sdf.format(d)); // You need format method
which outputs:
2013-10-25 17:35:14 EDT
What are the people answering not getting here is more the question:
2013-10-25 17:35:14 EDT != Sat Jan 26 03:05:14 IST 2013
I think it is because 'EDT' is the timezone and so, when it is 17:35 in EDT is is 3:05 in the UK, ignoring Daylight saving adjustments.

Converting a string to Date object

I am reading date values from a file in which i am reading it as string object.
The date values varies in many format for example sew below:
01-Mar-2012
01/12/2012
01-12-2012
01.12.2012
01.Mar.2012
07/01/2008 12:00:00
07/01/2008 12:00:00 AM
What ever be the format i want the date object in format dd/mm/yyyy.
There is so many combinations.
SimpleDateFormat expect me to provide the pattern to format it .
Is there is any way to guess the pattern or create a date object from the given string?
how can you know if 12-6-2012 is 6th december or 12th june?!
what you could do is defining an array with all possible patterns.
then try to parse the date for each array entry (if it throws an exceptionen try the nexct pattern and so on)
i know that this is a pretty ugly attempt but it works!
What ever be the format i want the date object in format dd/mm/yyyy.
A java.util.Date object does not have a format - the only information it contains is an instant in time (specifically, the number of milliseconds since 01-01-1970, 00:00:00 GMT).
So, you cannot have a "date object in format dd/mm/yyyy". Date objects don't have a format, just like numbers don't have an inherent format.
If you want to display the date in the format dd/mm/yyyy, then you have to convert it to a string first using a SimpleDateFormat object; you specify the format on the SimpleDateFormat object (not on the Date object itself).
// NOTE: use MM instead of mm; MM = months, mm = minutes
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
// Display the date in the format dd/MM/yyyy
System.out.println(df.format(now));

How to modify my code to only get the time portion of a date?

I've got the following code:
Date time = new SimpleDateFormat("HH:mm").parse("8:00");
When I call time.toString(), the following is produced:
Thu Jan 01 08:00:00 CET 1970
Is there any way I can extract just the 8:00 from it? I have searched far and wide and have not found any way to do it using the standard SimpleDateFormat.
When I call time.toString(), the following is produced
Yes, it would be - because you're calling Date.toString. A Date value has no concept of format.
Is there any way I can extract just the 8:00 from it?
Whenever you want to convert to a string, you should use a DateFormat. So use the same format that you parsed in.
Alternatively, use Joda-Time, which has a LocalTime type specifically for "time of day", and has a handy parse method. You should still use a formatter every time you want to convert to a string, but at least the value will be easier to work with and more descriptive before then.
LocalTime localTime = LocalTime.parse("8:00");
To format this, you can use something like ISODateTimeFormat.hourMinute() or if you might have more precision, perhaps ISODateTimeFormat.hourMinuteSecond() - see the docs for all of the many options available.
recycle your original SimpleDateFormat Object
SimpleDateFormat format = new SimpleDateFormat("HH:mm")
Date time = format.parse("8:00");
String outString = format.format(time);
in case you were wondering, Here's some more information on DateTime Masks
Use the same SimpleDateFormat instance to format date into string.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date time = sdf.parse("8:00");
System.out.println(sdf.format(time));
This will print:
08:00
java.util.Date class represents a specific instant in time, with millisecond precision.
API says java.util.Date.toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
In order to format date's use SimpleDateFormat class
System.out.println(new SimpleDateFormat("HH:mm").format(time));

Parsing of string to Date Object

I have string "Tue Nov 12 2010",I want to parse it in java.util.Date object.
I write below code for this
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date= format.parse("Tue Nov 12 2010");
It is giving exception like below:
java.text.ParseException: Unparseable date: "Sun Nov 21 2010"
Not getting what is wrong with it???
Your format is wrong - if you specify a format dd/MM/yyyy, then you need to supply the string to be formatted in the corresponding format (!) e.g. 21/11/2010.
Ofcourse because it is not in format
format for Tue Nov 12 2010 should be EEE MMM dd yyyy
Have a look at docs
Learn to read code and use common sense.
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date= format.parse("Tue Nov 12 2010");
This should be blatantly obvious that the format specified doesn't match the string being parsed. They're on adjacent lines, right next to each other. It doesn't get more straightforward than that.
You need to be able to see something like this if you are to be a successful programmer. If you can't see this, how are you ever going to find similar problems when the two lines causing problems aren't even in the same source code file?
My advice is to take some personal responsibility for learning how to read and debug code. Something like this should be a huge red flag right when you type it that the two lines of code don't match up.
The date format you have created
new SimpleDateFormat("dd/MM/yyyy");
Will only parse dates of that form. I.e. 05/10/1989
You'll need to change the format something more appropriate.
To parse the date you need to provide correct format. For the sample date give by you the format would be "EEE MMM dd yyyy"
You are using the wrong format for the date. To parse it according to your string format use "EEE MMM dd yyyy"

Categories

Resources