Android unix timestamp - Converter [duplicate] - java

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 8 years ago.
In my android app I'm creating a timestamp this way:
final BackupInfo backupInfo = new BackupInfo(description, System.currentTimeMillis(), backupContacts.size());
eg, using System.currentTimeMillis()
Now I convert it back to date format using:
public static String getDate(long time)
{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
return date;
}
And it works fine.
But now I'm receiving a timestamp from a server and the date String I receive from getDate is not the correct date.
Practical case:
My app generates this timestamp: 1403022230766
getDate returns this date: 17-06-2014 05:23:50 which is correct to my eyes.
Now the problem comes in, I get this timestamp from the server: 1403022360
getdate returns this date: 16-01-1970 18:43:42 which is totally wrong, it should be close to the timestamp generated by my app.
The timestamp returned by the server is 3 digits less in size. But if I go to an online converter, like this one and I put 1403022360 (the TS generated by the server) I get a correct date.
Can anyone explain me why this difference and what am I doing wrong in my getDate method that I can't decode the timestamp received from the server?

Your server is returning your timestamp in seconds, so multiply by 1000 to get milliseconds.
The online converters work properly because they assume that the that if the number is large enough, then it is in milliseconds and if it's short then it is in seconds.
Java/Android dates are all long types so they can hold milliseconds for additional precision.

Related

Timezone conversion in Grails leads to wrong dates

I'm about to deal with time zones in Grails (Java). Here Java 7 is used and Grails 2.3.7.
I have a WebApp where each user is assigned a timeZoneID. If a user enters a date, it only consists of day, month and year. I want to set the time automatically.
The date entered by the user (e.g. 01.10.2018, german format) should be saved in the DB (MySQL) in UTC format.
When the date is displayed to the user, it is formatted according to the user's time zone.
Many timeZoneIDs work fine with my code (Europe/Berlin, Hont_Kong, ....), but America/New_York for example doesn't and I don't understand why.
The code to parse and save a date is as follows:
//endDate is 31.10.2018
def format = messageService.getMessage(code: 'default.date.short.format')
//--> dd.MM.yyyy for DE and MM/dd/yy for EN
println("Use format: " + format)
SimpleDateFormat sdf = new SimpleDateFormat(format);
//set timezone (America/New_York)
sdf.setTimeZone(TimeZone.getTimeZone(user.timeZoneID))
//parse endDate
Date parsedEndDate = sdf.parse(endDate)
//create a calendar instance (e.g. America/New_York)
Calendar calendarEnd = Calendar.getInstance(TimeZone.getTimeZone(user.timeZoneID));
//set time
calendarEnd.setTime(parsedEndDate);
//set hour/minute automatically
calendarEnd.set(Calendar.HOUR_OF_DAY, 23)
calendarEnd.set(Calendar.MINUTE, 59)
//at this point it should be 31.10.2018, 23:59 (german format, timezone America/New_York)
//Convert to UTC before saving date in DB (MySQL)
calendarEnd.setTimeZone(TimeZone.getTimeZone('UTC'))
//save the date
def obj = new Foo(date:calendarEnd).save(flush:true)
The code inside my view (gsp) to display a date is as follows:
<g:formatDate
timeZone="${user.timeZoneID}"
date="${fooInstance?.calendarEnd}"
format="${message(code: 'default.date.format', default: 'MM/dd/yyyy, hh:mm a')}"/>
Inside the DB I get 2018-11-01 00:59:00
Inside my view (GSP) it results in 31.10.2018, 19:59, instead of 31.10.2018, 23:59
Thank you very much for your help.
The problem is in convert step:
//Convert to UTC before saving date in DB (MySQL)
calendarEnd.setTimeZone(TimeZone.getTimeZone('UTC'))
Because you are just changing the time zone so it is using the given time and date as if it is the UTC time zone.
Java 1.7 and before are somewhat unwieldy in regards to the Time API so a lot of people use Joda Time.
Otherwise you can use the advice from this question resulting in something like:
calendarEnd.add(Calendar.MILLISECOND, TimeZone.getTimeZone('UTC').getOffset(parsedEndDate.getTime())
This is not tested and could be wrong as the offset calculation might be diffrent

Java iso 8601 universal date time format [duplicate]

This question already has an answer here:
in java I need define date in this format 1999-05-31T13:20:00-05:00 [duplicate]
(1 answer)
Closed 5 years ago.
I want this result on date time: 2008-10-31T15:07:38.6875000-05:00, please help me how i get this result?
I am using following code but unable to get required response.
TimeZone tzone = TimeZone.getTimeZone("UTC");
DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
String nowAsISO = dateformat.format(new Date());
You are quite right:
Your format expression is missing seconds :ss, millisecond .SSS (many S for how many digit you want) and the Z timezone tag without '
Using single quote ' in the expression will exclude everything included in them from parsing, ergo you will have it printed like a string.
TimeZone tzone = TimeZone.getTimeZone("UTC");
DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
String nowAsISO = dateformat.format(new Date());
You can see every possible pattern here

Why are the get methods crossed out in this code? [duplicate]

This question already has answers here:
Code fragments are being struck out in Eclipse, why?
(3 answers)
Closed 7 years ago.
I have a piece of code here to calculate someone's age with the SQL date type in java.
The code works fine, but however you can't see it in the code pasted here, but in my netbeans environment the get methods are crossed out, but only in this line:
LocalDate datumDB = LocalDate.of(gbdat.getYear() + 1900, gbdat.getMonth() + 1,
gbdat.getDate());
someone any idea why?
this line isn't crossed out:
int leeftijd = datumVanVandaag.getYear() - datumDB.getYear();
this is my code:
private void checkSpelerGeschiktVoorPloeg(Persoon p) {
Date gbdat = p.getGbDatum();
LocalDate datumVanVandaag = LocalDate.now();
LocalDate datumDB = LocalDate.of(gbdat.getYear() + 1900, gbdat.getMonth() + 1, gbdat.getDate());
int leeftijd = datumVanVandaag.getYear() - datumDB.getYear();
}
The strikeout indicates that those methods are deprecated. You should use either java.util.Calendar or the new Java 8 Datetime API (which is the new-and-improved API that the LocalDate you're using is part of) to calculate these values for a date.
For instance the API document says:
#Deprecated
public int getYear()
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Comparing to get seconds difference between java and mysql datetime

I read a mysql date time field into one string e.g.
String arriveTime = rs1.getString("arriveTime");
Next step I try to get the current date and time using java to be similar format like the one I got from mysql.
DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTimer=null;
Date date = Calendar.getInstance().getTime();
currentDateTimer=outDf.format(date);
How can I minus the currentDateTime and arriveTime to get the net results in seconds. I would prefer to do it purely via java
First, I would not read a MySQL date-time into a String. I would change this,
String arriveTime = rs1.getString("arriveTime");
to
java.sql.Date arriveTime = rs1.getDate("arriveTime");
Then you can use basic subtraction to get the result in milliseconds, then divide by a thousand to get that in seconds - so
long diff = new java.util.Date().getTime() - arriveTime.getTime();
System.out.println(diff / 1000);
I read a mysql date time field into one string
If the column is varchar type it is ok you can read it using resultsetObject.getString()
But if your column type is Date then is it always recommended to get the value using resultset.getDate()
Mysql stores date in the format yyyy-MM-dd
I try to get the current date and time using java to be similar format
like the one I got from mysql.
When you do resultset.getDate() it will give you the java.sql.Date in format yyyy-MM-dd

How to format java.util.Date to a date in "MM/dd/yyyy" format in ruby?

I want to convert a Java object to be formatted in ruby.
I used the following code
def format_date(date,date_format)
return Date::strptime(date, date_format)
end
date is an instance of java.util.Date
date_format = "%d/%m/%Y"
I am getting the following error in ruby
private method `sub!' called for #<Java::JavaUtil::Date:0x150ea09>
convert to JRuby Time and use strftime like this:
def format_date(date, date_format)
t = Time.at(date.time/1000)
return t.strftime(date_format)
end
Java Date time Method gives the number of milliseconds since January 1, 1970, Ruby Time number of seconds since that time.

Categories