I have a strange situation.
In my application we are inserting a record with the current date (MM/dd/yyyy) when users access something in the application.
Sometimes the date is getting inserted with a wrong value that isn't the current date. (Ie: '21/09/2014', '13/09/2180', '22/08/2179'). We are using JPA to insert the record from JAVA. Please help me to find out the issue or solution for this.
Below is the code, where I am preparing/passing the value for Domain object.
Date curDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
UserAccessObj.setAccessedDate(sdf.parse( sdf.format( curDate ) ));
Here setAccessedDate(Date) is java.util.Date setter method in domain object.
So, what might be the issue? I am not able to trace the issue.
Instead of this:
UserAccessObj.setAccessedDate(sdf.parse(sdf.format(curDate)));
Try this:
UserAccessObj.setAccessedDate(curDate);
Is
sdf.parse( sdf.format( curDate ) )
strictly necessary ? You're taking a date, converting it to a string, and then parsing it as a date ? I suspect you're doing this to get rid of the time component of the (misleadingly-named) Date object ? I think using the Calendar class as per the answer in this thread is faster/safer. The best answer is to use the Joda-Time API.
I don't know if it's causing your problem, but it's adding unnecessary complexity. Note also that SimpleDateFormat is not thread-safe, and if the above code shares an instance of a SimpleDateFormat that would definitely account for peculiar behaviour. Again, Joda-Time provides thread-safety in this domain.
I think you can do is use Calendar object to get the current system time
Calendar cal = Calendar.getInstance();
and then convert it into the SimpleDateFormat.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.format(cal.getTime());
and then you have your own code
UserAccessObj.setAccessedDate(sdf.parse( sdf.format( curDate ) ));
Hope it helps :)
Save the input date into DB in this format : "yyyy-MM-dd". Correct date will be saved.
Related
I know that Date class can be really painful at times.
Could you please give me some painkillers in the form of the piece of advice on how to subtract time?
What I have is:
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
String s = "13.04.2015 16:00";
String s2 = "13.04.2015 15:30";
Date date = format.parse(s);
System.out.println(timeFormat.format(date.getTime() - format.parse(s2).getTime()));
This gives me 02:30:00, but I'd love to get 00:30:00 :)
I suggest to force common TimeZone for both SimpleDateFormat:
format.setTimeZone(TimeZone.getTimeZone("UTC"));
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
before formatting date.
I'm not sure if you are stuck to Java Date class by some requirements, but if you are working with date and time a lot in your application I recommend Joda-Time library. It solves many problems out of the box and allows executing operations on date and time in easier way.
I want to insert into a Mysql column (DATETIME column) a time & date . For that purpose i use
the DATETIME field .
But on the JAVA side , I need to have a Date object with the time & date .
Consider the code :
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str = dateFormat.format(cal.getTime());
System.out.println(str);
This code produces :
2014/03/19 01:11:35
How can I convert it to a Date object in the format yyyy/MM/dd HH:mm:ss , so it would be
possible to put it in the mysql column of DATETIME ?
Much appreciated
The getTime() method of Calendar returns a Date object.
For JDBC, you'll use a java.sql.Timestamp to preserve the time component. (I think a java.sql.Date loses the time component.)
For example:
preparedStatement.setTimestamp(new java.sql.Timestamp(cal.getTime()));
First point: Date objects have no "format" - they just represent an instant in time.
If you print them, you get the default toString() implementation for Date.
Second point: You don't need to format a Date to use it with JDBC.
You should use a prepared statement, then call setObject(), to set the parameter value - the JDBC driver will do the rest, including wrapping in quotes if that's required for the data type.
Final point: Never use Calendar unless you have to.
In this case, simply new Date() will do the job.
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);
Hi I want to iterate through a date range without using any libraries. I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. I was wondering if anyone can help. Thanks
String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");
Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
doSomethingWithTheCalendar(calendar);
calendar.add(Calendar.DATE, 1);
}
Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string.
Use class Calendar for date arithmetic. It has an add method to advance the calendar, for example with a day.
See the API documentation of the classes mentioned above.
Alternatively, use the Joda Time library, which makes these things easier. (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time).
Good day Lovely people
Please help a brother out. Well I'm a master in visual basic but in java let me rather not say.
In VB here are my methods:
System.DateTime.Now.ToLongTimeString()
System.DateTime.Now.ToString() + "/" + System.DateTime.Now.Month.ToString() + "/" + System.DateTime.Now.Year.ToString()
The first method will return the exact time e.g = 12:08:36 AM
And the second method will return the exact date e.g = 2012/09/26
I want to get the very same results but using java.How do i go about doing that.
Oooh Thanks in advance.
In .NET, DateTime.Now gives you the local date and time, in your local time zone.
If you use new Date() or the like in Java, it will give you a value which has no awareness of time zones. To take time zones into account, you should either create a Calendar which has the right time zone, or if you want to create an appropriate string you should use SimpleDateFormat - again, set to the right time zone before formatting. For example:
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
format.setTimeZone(...); // Whichever time zone you want
String text = format.format(new Date()); // "now"
Also note that Joda Time is a much better Java API for date/time than the built-in Calendar and Date classes.
Finally, your second piece of sample code in .NET is buggy - you should only evaluate DateTime.Now once; ideally just passing in a format string e.g. DateTime.Now.ToString("yyyy/MM/dd"). Even if you want to convert each bit to a string separately, however, you fetch the value once to a local variable and then reuse it. Otherwise, if you execute that code around midnight, the date can change - so for example, if you executed it just before the start of 2013, you could end up with a string of "2012/12/1" or "2012/1/1" neither of which would be correct.
Use java.text.SimpleDateFormat class to format date and new java.util.Date() will create an instance system date default.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("hh:mm:ss a");
System.out.println(dateFormat.format(new Date)); //2012/09/26
System.out.println(dateFormat1.format(new Date)); //12:08:36 AM
To get the object representing the current date, you can use just new Date(), to format it, use SimpleDateFormat.