util.date to sql.date giving the wrong date - java

String d = request.getParameter("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("mm-dd-yyyy");
java.util.Date utilDate = dateFormat.parse(d);
java.sql.Date date = new java.sql.Date(utilDate.getTime());
The above code is to get a date from a form and get it into sql.date format to use in a prepared statement, however the date being produced is wrong, 03-14-2012 is being converted to 2012-01-14 +00:00:00
Am i doing this the right way?

Your DateFormat is incorrect mm are minutes, MM are months.
Regards

As burna has said, your date formatting is incorrect. For a full list of formats, refer to: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
As you can see, months are defined by MM. For a Month-Day-Year date, you should be looking at the format: "MM-dd-yyyy" Hope that helps.

The problem is not with the call to the java.sql.Date constructor. If you print out utilDate you will see that the value is already wrong at that point.
The issue is your SimpleDateFormat string - it should be "MM-dd-yyyy", that is, with the M's capitalized. See the javadoc for all the conversion codes.

Related

Can't get date from DateChooserCombo

I'm trying to get the date from DateChooserCombo as follows
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
String date = sdf.format(dateChooser.getDate());
But the method getDate() gives me error (illegal forward reference). I have also tried with getSelectedDate() but it's the same. What can I do?
Anyway I'm using Apache Netbeans 12.1 and the date picker should be this one:
https://github.com/vadimig/jdatechooser
Thanks.
I downloaded the JDateChooser code from the link you provided in your question. There is no getDate() method in class datechooser.beans.DateChooserCombo. There is a getSelectedDate() method which returns an instance of class java.util.Calendar.
Also, according to the documentation for class java.text.SimpleDateFormat, the pattern YYYY-MM-DD is a valid pattern but I don't think it's the pattern that you want. D means day in year which means that 27th February is the 58th day of the year. You probably want d. Similarly, Y means Week year whereas you probably wanted y.
So, in order to get a string representation of the date that the user selected from the DateChooserCombo, you probably want the following code.
DateChooserCombo dcc = new DateChooserCombo(); // or however you create and configure it
Calendar cal = dcc.getSelectedDate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(cal.getTime());
By the way, it appears that JDateChooser development stopped seven years ago. Perhaps consider using JavaFX which has a DatePicker component which works with Java's date-time API.

Format a String to a Fixed Date at UTC+0 in Java

I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

How to convert a date having ordinal format 1st March 1994?

I want format a date given in the following format 1st March 1990. The date should be formatted to YYYY-MM-DD. I have the following code. It gives me an unparsable date. From this i can understand, this is not the correct way to format this date as its not a valid pattern.
public class DateFormattingTest {
public static void main(String[] args) throws ParseException {
String dateString = "1st March 1984";
dateString = dateString.replaceFirst("[a-zA-Z]{2}","") ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy");
Date rightNow = simpleDateFormat.parse(dateString);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(rightNow);
System.out.println(formattedDate);
}
}
I have revised and looked for date formatting patterns as well. I cannot find something related to this pattern "1st March 1990". I don't want sample code for this issue. I want to find out what am i doing wrong in here? Can someone suggest an approach to parse such a date?
Thanks.
You have three problems.
First, you're trying to parse the date using the format YYYY-MM-DD. That's not the format of your data, which is why parsing is failing.
Second, you're expecting a Date object to retain information about a particular format. It doesn't. Instead, you would parse from one text format to a Date, and then use another DateFormat (with the desired output format) to format the Date into a String. Date.toString() will always use the same format, regardless of how you arrived at the Date.
Third, your format of YYYY-MM-DD isn't really what you want - you want yyyy-MM-dd. YYYY is the "weekyear", and DD is the "day of year".
I don't know of any SimpleDateFormat approach which would handle the ordinal part of your input string ("1st", "2nd" etc) - you'll probably need to put a bit of work into stripping that out. Once you've got a value such as "1 March 1990" you can parse with a SimpleDateFormat using the pattern d MMMM yyyy. Make sure you set the time zone and the locale appropriately.
Your date 1st was not incorporated into the Java DateFormat. If you can switch to 1 and use the appropriate DateFormat, the parsing of Date will work or else you would need to convert the ordinal number to number by stripping the suffix.
This might be a good related post to peek at.
The problem is that your dateString does not match the pattern specified in your simpleDateFormat format. It is expecting a date in the format YYYY-MM-DD, the meaning of these symbols can be found here.

I want to get a formatted Date in Java

I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);
I can't do this, because today is a Date, and format returns a String. I also have tried:
Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
today = myFormat.parse((new Date()).toString());
}catch(Exception e){
}
This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?
You are looking at Format and Date wrongly.
Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.
So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.
One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.
Edit:
Now if you want to strip some info from the date. Use
Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
rightNow.get(YEAR),
rightNow.get(MONTH),
rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();
There are other good soln like JodaTime
Ref:
GregorianCalendar
Calendar
Joda Time
I think what you are trying to achieve does not make sense.
A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).
I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:
Parsing a String representation into a Date object.
Converting a Date back into String representation to display it in a certain way.
Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.
you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,
Do all processing in the Date object itself and while displaying alone change to the required format,,

Code to convert seconds to Date and time combination in java

I have seconds like below:
1320130800
I need to convert the value into Date and Time Combination format. While formatting I got the result as follows:
Tuesday,November 1,2011 2:00,AM
But the correct result is as follows:
Tuesday,November 1,2011 7:00,AM
For the above format conversion I used the below code:
long millis = 1320130800*1000;
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
Can any one guide me to get the correct answer?
Sounds like it's just a time zone issue - you need to set the time zone for the formatter:
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
(Note that in your sample code, long millis = 1320130800*1000; doesn't work as it performs the multiplication in 32-bit arithmetic; you need something like long millis = 1320130800L*1000;.)
Use the Calendar API instead.
After you have the Date object, construct a Calendar object (getInstance() returns one with the default Time Zone) and do setDate(Date) on it and parse it like that.
Alternatively, you can take a look at Joda Time APIs since they are easy to use.
Regards!

Categories