Java DateTime viewing [duplicate] - java

This question already has answers here:
String -> java.util.Date -> java.sql.Date (with time stamp)
(3 answers)
Closed 6 years ago.
Hello i'm defining a variable in which i want to stock date-time input.
I gave this variable a format which is yyyy-mm-dd hh:MM.
But in the database it keeps showing me only this format yyyy-mm-dd without hh:MM
The code
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd hh:MM");
java.util.Date date = sdf1.parse(rs.getString("dateMaint"));
java.sql.Date sqlStartDate = new Date(date.getTime());
mc.setDateMaint(sqlStartDate );

Also check if the database data type for your data is correct. This is dabase vendor dependant, for example an Oracle date type contains both time and date, but MS SQL server date means only date part: https://msdn.microsoft.com/en-us/library/bb630352.aspx

public static java.sql.Timestamp convertToSqlDateTime(Date utilDate){
return new java.sql.Timestamp(utilDate.getTime());
}
Normally, java.sql.Date only returns a date-only value and time will be discarded. So, in order to get time also, java.sql.TimeStamp must be used.
TimeStamp constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
For this purpose, utilDate.getTime() is used to return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date Object.
For more information link: Source

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);

Android timestamp to local user time or date [duplicate]

This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 5 years ago.
How can I convert minutes from Unix timestamp to date and time in java? For example, timestamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.
I want to convert 1372339860 to 2013-06-27 13:31:00 GMT.
Edit: Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)
Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

SimpleDateFormat parse is changing time according to timezone [duplicate]

This question already has answers here:
java.sql.Timestamp: changing timezone of Timestamp
(2 answers)
Closed 6 years ago.
I get timestamps as a String in a stream and they are of the format "2016-12-08 05:44:48 <timezone like IST, UTC>" and "2016-12-08 05:44:48 <timezone like +0000>"
I want to convert the string to java.sql.Timestamp so I wrote a function as follows
private static Timestamp convertToTimestamp(String s) throws ParseException{
String dateFormat = new String("yyyy-MM-dd hh:mm:ss z");
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date d = sdf.parse(s);
return new Timestamp(d.getTime());
}
When I run
Timestamp t = convertToTimestamp("2016-12-08 05:44:48 UTC");
System.out.println(t);
The output is 2016-12-08 11:14:48.0
It is automatically converting into IST (Probably my JVM default).
How to make the change so that the output time not changed to IST and is same as input?
Java's java.util.Date and java.sql.Timestamp do not store timezone.
They always track time in UTC.
When parsing a date string that includes a timezone, the string is correctly parsed and adjusted from the given timezone to UTC.
When parsing a date string without timezone, the string is parsed in the JVM's default timezoneand converted to UTC, unless another timezone has been explicitly given to the date parser (commonly SimpleDateFormat).
When displaying (aka formatting) a Date/Timestamp, it will be shown in the JVM's default timezone, unless otherwise specified.
The Date/Timestamp objects cannot store a timezone, so they cannot remember what the original timezone was.
If you need that, use Java 8's ZonedDateTime.
You have to ignore the time-zone when parsing the date
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Convert BigInt timestamp to Date in java? [duplicate]

This question already has answers here:
How to convert currentTimeMillis to a date in Java?
(13 answers)
Closed 5 years ago.
I did some searched on web about BigInt data conversion into date while I've found plenty of same question but non of them seems to work. There is 13 digit's data 1435555326831 into my database and I think this is UNIXTIME, now I want to convert it into yyyy-MM-dd HH:mm:ss form. Thank you
You can first convert the number into a long (if you receive a BigInteger, you can call BigInteger.longValue()).
Then you have two options. With the standard java.util.Date you can use:
long millis = 1435555326831L;
Date d = new Date(millis);
You can then format the date with a SimpleDateFormat for output.
If you can use Java 8's new Time API, you can create an instant and convert it to the desired time zone (your computer time zone in my example below):
Instant instant = Instant.ofEpochMilli(millis);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(fmt.format(instant.atZone(ZoneId.systemDefault())));
Note that these conversions only work if BigInteger is smaller than the maximum long size, not in general. This shouldn't be an issue, since the maximum value of a long is 2^63 - 1, but if your BigInteger is user input, you need to check for this.
Your data is on Unix timestamp and you can simply convert it by using new java.util.Date()
and here is the example of it
Java: Date from unix timestamp

Storing java util date into mysql as a timestamp

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());

Categories