Storing java util date into mysql as a timestamp - java

I am using JPA and MySQl
In my domain object i have a date field as
#Temporal(TemporalType.TIMESTAMP)
private Date lastSeenDate;
From my UI the date goes as a String in format dd-mm-yyyy
I used
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
final Date date = format.parse(dateString);
but for String date
06-06-2013
the date stored in mysql is
0011-12-04 00:00:00.0
How do I store it into mysql to match the mysql format

The class Date represents a specific instant in time, with millisecond
precision.
From: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
The date class always has a time component.

All dates in Java are essentially timestamps as they represent a single millisecond in time.
There's no way I can think of to deal only with dates but you might want to have a look at java.util.Calendar. If you can set the hours, minutes, seconds and milliseconds all to zero (or other defined time) you can then work with days, months and years more naturally. It's not a very good offering but it works well enough.

According to JavaDocs: java.util.Date allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
So, it works like a database Timestamp. It would always have a time component although it may be all zeroes that is representing a midnight. But, you could use the same SimpleDateFormat to print out the java.util.Date without its time component.
final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final Date utilDate = sdf.parse("2013-06-20");
System.out.println(sdf.format(utilDate)); // prints back 2013-06-20
Or, you may want to look into java.sql.Date which does not have a time component.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Related

#JsonFormat converts Date with incorrect timezone

I have a simple POJO with a Date field with initial value coming in:
1985-09-17T01:00:00.000+0400
then this Date value gets mapped to a DTO with the Date field annotated:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssX")
private Date dateOfBirth;
Then the result is shown:
1985-09-16T21:00:00Z
I have tried setting the timestamp property in #JsonFormat, but that didn't help and the date is still invalid.
How can I correctly convert the date?
The value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.
So in your case it's better to use ZonedDateTime class if you use java 8 ZonedDateTime
Both dates represents the same instant:
1985-09-17T01:00:00.000+0400
1985-09-16T21:00:00Z
When you print dates in java it uses the current timezone of the VM, but internally the Date class stores that information in a long representing the time in milliseconds since the epoch.
If you like you can get the a String representation of the date using a custom timezone using the setTimeZone method of DateFormat:
Sets the time zone for the calendar of this DateFormat object.
Here a simple snippet of code:
Date date = ...
DateFormat formatter = ...
TimeZone timeZone = ...
// Set a custom timezone
formatter.setTimeZone(timeZone);
// Get a string representation of the daet with a custom timezone
String formattedDateWithCustomTimezone = formatter.format(date);

In Java, Can the Date type just hold MM-dd-yyyy or just hh:mm:ss?

I am converting epoch format time to the normal format, but when I convert it to date I get, MM-dd-yyyy hh:mm:ss.
If I want to single out just the date or the time I have to use SimpleDateFormat. But this returns a String. I was wondering if there was a way to make this string a Date type.
The type java.util.Date is actually a timestamp, it is not much more than a wrapper for a number of milliseconds since 01-01-1970, 00:00:00 UTC. (The class name Date is unfortunately badly chosen).
It is not very well suited for holding just a date or just a time value.
If you are using Java 8, use the new date and time API (package java.time); use for example LocalDate if you need to store a year/month/day, or a LocalTime if you need to store just a time-of-day (hours, minutes, seconds, milliseconds).
If you are using Java 7 or older, consider using the equivalent classes in the Joda Time library.
You can format the date as MM-dd-yyyy HH:mm:ss not (MM-dd-yyyy hh:mm:ss)
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
DateFormat dateformat= new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Date date = dateformat.parse("01-25-1988 23:54:59");
System.out.println(date);
System.out.println(dateformat.format(date));

How to change date format from setting it reference in date data type

I am getting date in an date object
Date s = ((java.util.Date) ((Object[]) object)[++i]);
i need to set this format 20130509 06:00
so for this I have choosen ..
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
String s1 = sdf.format(s);
now again my task is to put back in date object that string s1, please advise how to achieve this
Date doesn't have a textual format - or even a time zone or calendar. It's just a number of milliseconds since the unix epoch. There's nothing to set within Date.
You need to differentiate between your fundamental data, and a textual representation of that data - in the same way as the int value 16 is the same as 0x10. I can't think of any time where I've found it appropriate to carry a textual representation of a date around with the date itself. In various places in your program you may well find that you need different representations for the same date - but it's usually the same representation for all dates at that specific part of the program.
As an aside, you should consider using Joda Time instead of java.util.Date - it provides you with a much richer set of types to consider, so you can express what your program is actually dealing with (just a date, just a time, a date/time in a particular time zone etc).
Ideally, you shouldn't try to translate to String format and back again. You should persist the original value and just use the String format for display purpose only.
Otherwise, you can use SimpleDateFormat.parse method.
I recommend using Joda time... how given what you've got you can just do
sdf.parse
#Test
public void testDateStringConversion() throws ParseException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
String s1 = sdf.format(date);
Date date2 = sdf.parse(s1); // seconds won't match
String s2 = sdf.format(date2);
assertEquals(s1, s2);
}

Subtract date to get yesterday date [duplicate]

This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
I have these codes to get the date today in my server
DefaultTableModel dnow = MyDB.DataTable("SELECT date_format(now(),'%m-%d-%Y')");
and these code for the formatting for the date.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
now how can I get the date of yesterday?
should I just minus it with one?
An alternative approach is to do the math in SQL. The statement may vary depending on what database platform you're using.
DefaultTableModel dnow =
MyDB.DataTable("SELECT date_format(now() - INTERVAL 1 DAY,'%m-%d-%Y')");
No, build a Date (or better yet use joda's DateTime object) and then do your arithmetic. I will give you two solutions, one with Joda and the other without, starting with without:
Date d = format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()));
d.add(Calendar.DATE, -1);
Now, using joda:
DateTime d = new DateTime(format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()))).minusDays(1);
This should work perfect for you,
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());
This will simply subtract 1 day from the current calendar date, providing you yesterdays date
If you store your timestamps internally as POSIX times (milliseconds since MN Jan 1, 1970) then you can add or subtract a day to any time stamp as easily as:
Date today = new Date(); // today
Date tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); // tomorrow
The huge bonus to POSIX time is that it is always in UTC. UTC is a global, "fixed" point of reference. Then if you need to need to have this date displayed for the user in any time zone, in any daylight savings zone, for any place that is accounted for in the Olson Time Zone database, you can simply create a Calendar:
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setCalendar(gc);
sdf.applyPattern("MM-dd-yyyy");
// Now your formatter is set with the pattern and a time zone-aware Calendar.
// The world is at your command
String myOutput = sdf.format(tomorrow);
I highly recommend dealing with timestamps internally in your data model in some form of UTC representation. Doing date arithmetic with POSIX time (or Julian Day Numbers, or Modified Julian Day Numbers) is easy peasy, and the Java date/time API has enough capability to deal with most local time conversions without much fuss from you.

SimpleDateFormat not showing the right date format

I have a DateTime field in my SQL database holding and when I try to show it in my JSP page and format it using "dd-MM-yyyy hh:mm:ss", it displays correctly only the date part. For example, for the date "2012-01-19 12:13:48" stored in the database it shows "19-01-2012 12:00:00". What may be the problem?
Code:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.format(rs.getDate("comment_date")); //rs -> ResultSet
From the javadoc for java.sql.Date:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
In order to preserve time information as well, you should be using java.sql.Timestamp. In other words, change rs.getDate() to rs.getTimestamp().
An interesting date/time library you could have a look at is Joda Time. It solves many issues of the date/time implementations in the standard library.

Categories