DateTime convertion in java - java

I have a date get saved in the database in IST format.
Date nowDate = new Date();
Date dateBefore = new Date(nowDate.getTime() - 7* 24 * 3600 * 1000);
System.out.println("Datebefore-->"+dateBefore);
Here in the above code dateBefore is get saved in the database.
From the database I am taking the data long value and I have to convert this into Google DateTime
Date dateBefore12 = new Date(longvalue);
com.google.api.client.util.DateTime dd = new DateTime(dateBefore12, TimeZone.getTimeZone("UTC"));
Now for example the output will be in the 2014-07-17T05:23:28.857Z which I have to pass to the Google You tube API.
Now from the response I will take Google DateTime, let say 2014-07-17T05:23:28.857Z which I have to increment the 1 minute and then convert it into long and save into db.
Convert the google DateTime to long.
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = dd.toString();
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(f.parse(input));
cal.add(Calendar.MINUTE,1);
Date time = cal.getTime();
long longvalue1 =cal.getTimeInMillis();
Now I will saved the data and try to retrieve it. It gives me back 2014-07-16T23:54:28.857Z.
But I need the save date value which I have increment by one minute in the format of google DateTime.

SimpleDateFormat also uses a time zone, due to an internal Calendar object, which defaults to the local time zone. If you don't want to use that default time zone, then before you call the format's parse() method, you should call setTimeZone() on it:
f.setTimeZone(utc);

Related

How can we convert Timestamp datatype in Java to UTC timezone in JPA entity Java?

We are using PO class to represent the sql DB and using Java JPA entity.In that class, we have one column as a field currentTime with Timestamp datatype and #version annotation from JPA.
#Version
private Timestamp currentTime;
whenever the entity gets updated, currentTime is updated with the latest time.
currentTime = new Timestamp(0); //this will create the new timestamp with current time.
but it’s currently taking the time from the server. I want to convert this time to UTC format before saving it to DB.
Anyone can help how can I convert the time to UTC time?
I had a similar problem when I needed to parse the time from server but I needed to convert this time to UTC format before storing this information int MySQL DB. This was my solution:
Instant dateConverted = LocalDateTime
.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH))
.atZone(ZoneId.of("Europe/Bratislava")).toInstant();
long epochTime = dateConverted.toEpochMilli() / 1000L;
Where dateTime is a String variable containing the date and time from server
And I have used DateTimeFormatter to format my time to appropriate format.
At the end I have added the zoneID of my timeZone and converted it to Instant
And at the end I have converted to seconds
Try below code,
currentTime = Timestamp.valueOf(LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String localTime = sdf.format(new Date(your_time_stamp));
Date date = new Date();
try {
date = sdf.parse(localTime);//get local date
} catch (ParseException e) {
e.printStackTrace();
}

Convert milliseconds to timestamp with UTC

I'm trying to convert milliseconds to Timestamp with timezone UTC but it doesn't work as is expected because it convert to my localdatetime.
I have tried following. While debugging the code I have found that when execute this: new DateTime(eventDate) it is working properly because it's value is 10:34:18.721 but later new Timestamp() change it to localdatetime.
long eventDate = 1566297258721L;
DateTimeZone.setDefault(DateTimeZone.UTC);
Timestamp timestamp = new Timestamp(new DateTime(eventDate).getMillis());
I expect to output as:2019-08-20 10:34:18.721 but actual output is: 2019-08-20 12:34:18.721
You can use java.time package of Java 8 and later:
ZonedDateTime zonedDateTime = Instant.ofEpochMilli(1566817891743L).atZone(ZoneOffset.UTC);
I don't understand why you are creating a new DateTime and then get the milliseconds from there, if you already have the milliseconds in the beginning.
Maybe I'm misunderstanding your problem. The milliseconds have nothing to do with the timezone. The timezone is used to compare the same moment in 2 different places and get the respective date. Here are my solutions
If you want a timestamp from milliseconds:
long eventDate = 1566297258721L;
Timestamp time=new Timestamp(eventDate);
System.out.println(time);
The result would be 2019-08-20 10:34:18.721 , also the wished SQL format
If you want to convert a moment from a Timezone to another:
You will get the moment in your actual timezone and transform it in a different one in order to see e.g. what time it was in an other country
long eventDate = 1566297258721L;
Calendar calendar = Calendar.getInstance();
calendar.setTime(eventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.format(calendar.getTime());
I hope those snippets could be useful. Happy Programming!
You can try the following,
long eventDate = 1566297258721L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String stringDate = simpleDateFormat.format(new Date(eventDate));
System.out.println(stringDate);
It gives me the following output.
2019-08-20 10:34:18 UTC

How do I touch a folder with current time using set last modified date & time?

I'm trying to update the last modified date of a specific folder, here's what I've got:
public void touchFolder(){
File folderToTest = new File("C:\\Temp");
SimpleDateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
String newTime = dateFormatUtc.format(new Date());
folderToTest.setLastModified(Long.parseLong(newTime));
}
I am just putting this code in a test case so don't worry about calling this method etc.
I'm getting errors with the parsing that date format as a long, what's the format used in setting the last modified date & time?
This is an example from the documentation, using java.nio.file.Files:
Path path = ...
FileTime now = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path, now);
I think you should just do folderToTest.setLastModified(System.currentTimeMillis());
In your code newTime is a formatted date 2018-12-19 15:21:31 which can't be parsed to Long. What you want to do is supply the time in milliseconds e.g.:
Date d = new Date();
file.setLastModified(d.getTime());
As per File.setLastModified() method javadoc:
time - The new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)

Converting a date a string to java.sql.Date format

I'm having an issue while trying to insert a date into an SQL server using Java:
//final String input = "20120823151034";
final String input = "06282013143533";
final DateFormat df = new SimpleDateFormat("MMddyyyyHHmmss");
final Calendar c = Calendar.getInstance();
c.setTime(df.parse(input));
//c.add(Calendar.MILLISECOND, 1);
String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);
java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());
System.out.println(sqltDate);
Here, I'm expecting the complete string being output as the year, month, day, hour, minutes, and seconds to be inserted into SQL server, but I'm only getting the year, month, and the date. What should I do to insert the date and the time into the database?
check your DATA type in database either it should be Timestamp or Datetimefor this purpose you can use database function NOW() for current date and time.and convert your date into timestamp
Timestamp timestamp = new Timestamp(new Date().getTime());
and insert this timestamp into database
java.sql.Date can be used to store only the year, month and day of the month. It can't be used to store the time of the day.
In order to store time, you would have to use Timestamp. In your above code, replace
java.sql.Date sqltDate= new java.sql.Date(parsedUtilDate.getTime());
by
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());
The above changes will make things work fine.

Parsing date with different time zones

Even with about 15 years in Java one always stumbles over the topic of handling dates and times...
Here's the situation: I get a timestamp from some external system as a String representation. The timestamp's semantic is that it represents an UTC date. This timestamp has to be put in an entity and then into a PostgreSQL database in a TIMESTAMP field. Additionally I need to put the same timestamp as local time (in my case CEST) into the entity and then into the database in a TIMESTAMP WITH TIME ZONE field.
What is the right way to ensure that no matter what the settings of the machine executing the code are, the timestamps get stored correctly in the entity (to make some validations with other UTC timestamps) and in the database (to use them in reports later on)?
Here's the code, which worked fine on my local machine:
SimpleDateFormat sdfUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
sdfUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcTimestamp = sdfUTC.parse(utcTimestampString);
// getMachinesTimezone is some internal util method giving the TimeZone object of the machines Location
Calendar localTimestamp = new GregorianCalendar(getMachinesTimezone());
localTimestamp.setTimeInMillis(utcTimestamp.getTime());
But when executing the same code on the server, it resulted in different times, so I assume that it's not the correct way to handle it. Any suggestions?
PS: I read about Joda Time when searching in this forum, but in the given project I'm not able to introduce new libraries since I only change an existing module, so I have to live with the standard JDK1.6
If I understand correctly, You need to set the timezone on the same data/calendar object that you are printing. Like this:
private Locale locale = Locale.US;
private static final String[] tzStrings = {
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
};
Date now = new Date();
for ( TimeZone z : zones) {
DateFormat df = new SimpleDateFormat("K:mm a,z", locale);
df.setTimeZone(z);
String result = df.format(now);
System.out.println(result);
}
if i set timezone to SimpleDateFormat it is working fine.
here is the sample code...
String date="05/19/2008 04:30 AM (EST)";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa (z)");
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
long millis = sdf.parse(date).getTime();
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(new Date(millis)));
I think you have to set the target time zone in you Calendar object. I think something like:
Calendar localTimestamp = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
localTimestamp.setTimeInMillis(utcTimestamp.getTime());
In other case Java takes the default system time zone for the Calendar instance.
You can do it by the below example code.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date1 = dateformat.parse(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
Date date2 = dateformat.parse(formatter.format(date));
// Prints the date in the IST timezone
// System.out.println(formatter.format(date));

Categories

Resources