Convert date format not working - java

hello guys I've been on this issue for 4 hours and I don't seem able to solve it.
I want the date selected using JDateChooser to be converted to this format dd-mm-yyyy but I couldn't do this.
This what I wrote but it prints the date as :Thu Aug 21 00:00:00 WEST 2014. I want it to be printed 21-08-2014
This is my code:
public void addIns() {
JTextField ch=(JTextField) dateChooser.getDateEditor().getUiComponent();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
try{
Date date = df.parse(ch.getText());
} catch(Exception e){System.out.println("wrong date");}
System.out.println(date); }

The format Thu Aug 21 00:00:00 WEST 2014 is the default format of the Date.toString method.
So, if you are expecting:
System.out.println(date);
To print 21-08-2014, then you are wrong.
You could:
in Java 8 use LocalDate and LocalTime, and have a decent toString (but that won't print 21-08-2014).
print the date with the format method, eg: df.format(date);
And, since you are using Swing - and Swing components - there is probably a better way to get or set the format on the component.

Related

How to convert to a GST date?

After doing a lot of google research I am posting this question here in this expert group.
I have found many related links but did not work in my case.
I am fetching a date value from database which comes in this format 2016-01-12 00:00:00.0. Now I want to compare this date with the date what user is entering from screen UI which comes in this format Thu Jan 13 00:00:00 GST 2016.
Now I want to compare these dates i.e. the date which was entered from screen (Thu Jan 13 00:00:00 GST 2016) should not be greater the or equal to the date fetched from the DB (2016-01-12 00:00:00.0).
For date comparing I am using:
public static boolean compareDates(Date fromDate, Date toDate) {
if (fromDate.before(toDate)) {
return true;
}
return false;
}
Which is not working because date format is not similar what I feel.
So I want to convert 2016-01-12 00:00:00.0 to Thu Jan 12 00:00:00 GST 2016.
Please help me in this as I am stucked since morning in this issue.
If you have any other solution to compare these dates, kindly suggest me.
I am calling the method compareDates(Date fromDate, Date toDate) from my bean class like this :
if (!TeltrackDateUtil.compareDates( installationdate, instrumentStaffLnkData.getEffectiveFrom() )) {
String erroMessage = resourceBundle .getString("instrument_add_edit_mandatory_check_linkage_effective_from_ins‌​tallation_date");
createFacesMessage(erroMessage, facesContext); canProceed = false;
}
in this installationdate = 2016-01-12 00:00:00.0 (from database) and instrumentStaffLnkData.getEffectiveFrom() = Thu Jan 14 00:00:00 GST 2016 which is from screen.
Adding some additional code:
In the DB (Oracle SQL developer), it is stored as datetime, in my Entity class it is Timestamp effectiveFrom.
In my ServiceImpl class I am setting this into a TO class variable :
InstrumentTO instrument = setEffectiveFrom(instrumentEntity.getEffectiveFrom());
Finally in bean class :
InstrumentTO instrument = instrumentService.getSelectedInstrument(instrumentId);
instrumentStaffLnkData.setInstrument(instrument);
Date installationdate = instrumentStaffLnkData.getInstrument().getEffectiveFrom();
and then calling compareDates().
You could parse your two different formats to date objects like this:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S", Locale.ENGLISH);
Date dateFromDatabase = df.parse("2016-01-12 00:00:00.0");
DateFormat df2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Date dateFromUi = df2.parse("Thu Jan 12 00:00:00 GST 2016");
compareDates(dateFromDatabase, dateFromUi);
But generally I would recommend you to use Joda Time for the reason #Srikanta has explained in his answer.
Opt for JodaTime library if you are using Java 7 or less. In Java 8, you can use the Time API. These libraries allow you to switch between the time formats including the time zones. There by making it easier to compare.

String to date not working properly [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I am trying from half an hour to convert string to date by using following code:
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
Date lastCharged = dateFormat.parse(lastChargeDate);
Every time I run this code the date returned by the system is Sun Dec 29 00:00:00 PKT 2013 Even if i changed the date manually same is the response by the system.
Any help in this regard a lot of work is suspended just because of this blunder.
DateFormat#parse() method just convert the String to Date. It doesn't change anything in the converted Date it means it doesn't store the format from which it is constructed.
Whenever you print the Date object again then it prints in its default toString() implementation that's what you are getting.
It you need to print it again in specific format then use DateFormat#format() method.
The format should be yyyy-MM-dd instead of YYYY-MM-dd.
Sample code:
String oldDate="2014-06-07";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date=dateFormat.parse(oldDate);
System.out.println(date);
String newDate=dateFormat.format(date);
System.out.println(newDate);
output:
Sat Jun 07 00:00:00 IST 2014
2014-06-07

Formatting a date in java

I have the two Date objects which I am trying to format from being in MM/DD/YYYY format to "yyyy-mm-dd HH:mm:ss" format.
The current approach I am using is to first format those dates using SimpleDateFormat which will return two Strings, then I have to convert this string back to Date to get the formatted final Date objects.
So I was wondering if there was a simpler way to change the Date object format without going in many steps?
Thanks
The format is irrelevant. Date simply represents the number of milliseconds since the Unix epoch.
Remember, Date has no concept of format, it doesn't care.
You should simply format the Date object with whatever formatters you need...
For example...
Date date = new Date();
System.out.println(date);
System.out.println(DateFormat.getDateTimeInstance().format(date));
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(date));
System.out.println(new SimpleDateFormat("yyyy MMMM EE").format(date));
System.out.println(new SimpleDateFormat("EEEE MMMM yyyy").format(date));
System.out.println(date);
Outputs...
Wed Jan 22 11:55:18 EST 2014
22/01/2014 11:55:18 AM
22/01/2014
2014 January Wed
Wednesday January 2014
Wed Jan 22 11:55:18 EST 2014
Note how the first and last values don't change. Date has no internal concept of format, that's the responsibility of the formatter.
For example, if I took the String value 22/01/2014 and parsed it back to a Date using SimpleDateFormat
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("22/01/2014");
And then outputted the date value...
System.out.println(date);
It would output something like...
Wed Jan 22 00:00:00 EST 2014
The format has being lost. It would need to use an appropriate formatter to change what is displayed

Can't make java.text.SimpleDateFormat to work

I have a Date object as follows:
java.util.Date d = new java.util.Date(System.currentTimeMillis()); // Mon Dec 23 14:57:28 PST 2013
I need to format the date to get another Date object with this format instead:
2013-12-23 14:57:28
I tried this code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
sdf.format(d); // d is still Mon Dec 23 14:57:28 PST 2013, no formatting.
I tried this code:
String s = d.toString();
try {
d = sdf.parse(s);
} catch (Exception e)
e.printStackTrace(); // java.text.ParseException: Unparseable date: "Mon Dec 23 14:35:48 PST 2013"
Would you please tell me what am I doing wrong? I googled searched it but the solutions to format a Date was more or less what I tried. Any help is greatly appreciated.
You don't understand what a Date is, and what format() does. A Date is just a number of milliseconds. Nothing more. It doesn't have any format. Formatting a date doesn't change the date at all. It returns a string containing a human readable representation of the date (like "2012-11-23" or "Monday, April 2").
So, the following instruction:
sdf.format(d);
is effectively a noop. You ignore the string that it returns.
If what you want is to have a specific format used when calling date.toString(), it's impossible. When you want to display a date in a specific format (yyyy-MM-dd for example), instead of doing
System.out.println(date);
use
DateFormat format = new SimpleDaeFormat("yyyy-MM-dd");
System.out.println(format.format(date));
All this is clearly explained in the javadoc. You should read it.
SimpleDateFormat, does not change the date format, it gives you a formatted date for display purpose only, not for anything else.
util.Date will always have one format (a long number of milliseconds) that you can format to any way you want in order to display using SimpleDateFormat. So in effect no matter what date you get you can format to what format you want.
If you explain why you are trying to do what you are trying to do, then maybe we can support you better.

What is the proper date format for a given date

What is the proper date format for this date instance ..
10/10/2011 2:36:00 PM
I've used this ..
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a");
edit
more code
Object temp = jsonArray.getJSONObject(i).get("STARTDATE"); // date object from webserive
Date appointment.mStartDate = formatter.parse(temp.toString());
but it returned this date in this format ..
Thu Nov 10 00:36:00 GMT+02:00 2011
but it returned this date in this format ..
Thu Nov 10 00:36:00 GMT+02:00 2011
You were thus doing System.out.println(appointment.mStartDate);? That's then perfectly fine. It's indeed the default format of the Date#toString() method. When you pass a non-String object to System.out.println(), then its toString() method will be called and the returned String will be displayed.
If you want to display it in the same format as you have retrieved it, then you should be using the SimpleDateFormat#format() method to convert Date to a String in the desired format:
String dateString = formatter.format(appointment.mStartDate);
System.out.println(dateString);
Use parseObject
Date appointment.mStartDate = (Date) formatter.parseObject(temp.toString());
There is four acknowledged variants:
US M/D/YY
ISO-8601 YYYY-MM-DD
JIS ?
EUR DD.MM.YYYY
What's your problem? The date appears to have been parsed correctly for a timezone of +2 hours. Naturally, when you simply print the toString description, the displayed value is in the default format -- to format the output you need to do a date formatter operation.

Categories