Getting today's UNIX timestamp with Calendar - java

I'm trying to get today's UNIX timestamp (seconds elapsed since 01/01/1970) at 00:00:00 with Java's Calendar:
public long getTodayTimestamp() {
Calendar c = Calendar.getInstance(Locale.getDefault());
c.setTimeInMillis(System.currentTimeMillis());
c.set( c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH),
0, 0, 0
);
return c.getTimeInMillis()/1000;
}
The problem is it returns 1409608800 for today (September 1st), but when I try to convert it with some converter (for example http://www.onlineconversion.com/unix_time.htm) I get Mon, 01 Sep 2014 22:00:00 GMT which is midnight September 2nd my local time. Basically the method is returning the timestamp 24 hours ahead of what I need.
Where did I screw up?

The online converter returns the date UTC+0
Your are in TimeZone +2.
That means: 22:00:00 (UTC+0) is 00:00:00 (UTC+2) in your timezone
so, when i am not wrong (i hope so), everything seems to be correct.
EDIT:
The problem in your case:
the method getTodayTimestamp() returns the timestamp in UTC+0
(getCalendar.getTimeInMillis returns in UTC+0)
That means 00:00:00 in your locale (UTC+2) is 22:00:00 in UTC+0
this is what the converter is showing!
see here:
http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#getTimeInMillis()

you can get the unix time the hard way :-)
at least you won't have to struggle with locales and etc
public class GetUnixTime {
public static void main(String[] args) throws IOException,
InterruptedException {
ProcessBuilder ps = new ProcessBuilder("date");
ps.redirectErrorStream(true);
Process pr = ps.start();
StringWriter sw = new StringWriter();
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sw.write(line);
}
pr.waitFor();
in.close();
sw.flush();
sw.close();
System.out.println(">"+sw.toString()+"<"); //parse this guy
}
}

tl;dr
java.time.Instant // Represent a moment in UTC.
.now() // Capture current moment in UTC.
.getEpochSecond() // Get the whole seconds component within an `Instant`, ignoring any fractional second.
Details
The answer by Ben appears to be correct.
Avoid j.u.Calendar
Date-time work is much easier with a decent library instead of the notoriously troublesome java.util.Date and .Calendar classes. Either use Joda-Time or the new java.time package in Java 8. Both of these libraries handle time zones explicitly and clearly.
java.time
Capture the current moment as seen in UTC using Instant. An Instant is always in UTC by definition.
Instant instant = Instant.now() ; // Capture current moment in UTC.
Apparently you want a count of whole seconds since the epoch references of first moment of 1970 in UTC.
long secondsSinceEpoch = instant.getEpochSecond() ; // Get the whole seconds component within an `Instant`, ignoring any fractional second.
Joda-Time
Example in Joda-Time 2.4.
DateTime nowParis = DateTime.now( DateTimeZone.forID( "Europe/Paris" ) );
DateTime nowUtc = nowParis.withZone( DateTimeZone.UTC );
long millisecondsSinceUnixEpoch = nowParis.getMillis(); // Some result when called on either nowParis or nowUtc.
long secondsSinceUnixEpoch = ( millisecondsSinceUnixEpoch / 1000L );
Call toString on those DateTime objects to verify their value.
Or in a single line.
long secondsSinceUnixEpoch = ( DateTime.now().getMillis() / 1000L );
Since we want only seconds since epoch of the current moment, the time zone does not matter.

Related

date.getTime() is shorter than System.getCurrentTimeMillis()

I'm trying to create a simple Alarm Clock, but I stumbled upon a problem that I can't seem to fix. I'm trying to parse a string to a date so I can get the difference between the current time and the time to set off the alarm.
Here's my code to parse the time:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
sdf.setTimeZone(getTimezone());
Date date = sdf.parse(args[0]);
Here's my getTimezone() method:
public static TimeZone getTimezone() {
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
return TimeZone.getTimeZone(name);
}
And here's my code for figuring out the difference:
long diff = date.getTime() - System.currentTimeMillis();
So my problem is that the date.getTime() returns 79680000, while System.currentTimeMillis() returns 1473538047978 (This is of course different every time, but for some odd reason, date.getTime() is not).
Which means that I get a negative number when trying to figure out the difference, and therefore I cannot use it.
EDIT: After a little bit of debugging, I realised that it has to do with the year, month and day not being set, however I do not know how to get those.
You did notice that date.getTime() returns 79680000 which is 22 hours and 20 minutes after 1 January 1970. The problem is (as you noticed) that you did not parse year, month and day.
You can do it by:
SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY hh:mm:ss");
Example input 20/04/2016 20:20:0 returns time as Mon Jan 04 20:20:00 CET 2016 (don't look at the timezone). It is 1451935200000 miliseconds after 1 January 1970.
Note: change string to match your format requirements (the syntax is self-explanatory).
The accepted answer by Ronin is correct. You are trying to put a time-of-day value into a date-time type.
java.time
Also, you are using troublesome old legacy date-time classes. Now supplanted by the java.time classes.
For a time-of-day value without a date and without a time zone, use LocalTime.
LocalTime alarmTime = LocalTime.parse( "12:34" );
Getting current time-of-day requires a time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalTime now = LocalTime.now( z );
But since we are setting an alarm, we care about the date too.
ZonedDateTime now = ZonedDateTime.now( z );
ZonedDateTime alarm = null;
if ( now.toLocalTime().isBefore( alarmTime ) ) {
alarm = ZonedDateTime.of( now.toLocalDate() , alarmTime , z );
} else {. // Else too late for today, so set alarm for tomorrow.
alarm = ZonedDateTime.of( now.toLocalDate().plusDays( 1 ) , alarmTime , z );
}
To calculate the elapsed time until the alarm, use the Duration class.
Duration untilAlarm = Duration.between( now , alarm );
You can interrogate the duration for a total number of milliseconds. But know that java.time classes are capable of handling nanoseconds.
long millis = untilAlarm.toMillis();
Updated.
You are using only time without a date with you date object in code (parses only time). If you add there date to you time, your date should be comparable to your System.getCurrentTimeMillis() call. And if you subtracting current millis from date in the past, you will have negative numbers. I prefer this convertion (date2 is after date1):
long diffInMillies = date2.getTime() - date1.getTime();
return TimeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);

Good way to convert integer YYYYMMDD into java.util.Date with local time zone

I understand this question could look like FAQ subject but critical things here is time zone and performance. I have integer YYYYMMDD date (20150131 is example). Here is good 'almost working' solution:
import org.joda.time.DateTime;
import java.util.Date;
// ...
public Date extract(final int intDate) {
Date result = null;
try {
result = new DateTime(
intDate / 10000,
(intDate / 100) % 100,
intDate % 100,
0,
0,
0,
0).toDate();
} catch (final IllegalArgumentException e) {
// Log failure
}
return result;
}
'almost' is because having 0x0126810d and EET (UTC+2 / +3 when DST) time zone I receive:
java.lang.IllegalArgumentException: Illegal instant due to time zone
offset transition: 1930-06-20T22:00:00.000
At least using JODA 1.6. I cannot switch easily.
But I'd like it to be 1930-06-21T00:00:00.000+02:00 and I don't care about UTC representation.
Is it possible at all (can java.util.date store such date)?
OK, any better high performance way to achieve this (JODA is just remedy here, not critical)?
Yes, I understand this time does not exist:
roman#node4:$ zdump -v Europe/Kiev | grep 1930
Europe/Kiev Fri Jun 20 21:59:59 1930 UTC = Fri Jun 20 23:59:59 1930 EET isdst=0 gmtoff=7200
Europe/Kiev Fri Jun 20 22:00:00 1930 UTC = Sat Jun 21 01:00:00 1930 MSK isdst=0 gmtoff=10800
java.time and LocalDate
No matter if using Joda-Time (as in your question) or java.time, the modern Java date and time API, I believe that the solution to your problem is using LocalDate. I suggest that you simply stick to this and neither use org.joda.time.DateTime nor java.util.Date. In particular not the latter, it was always poorly designed and is now long outdated.
I am presenting to ways.
int intDate = 19300621; // 0x0126810d
String asString = String.valueOf(intDate);
LocalDate date = LocalDate.parse(asString, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(date);
1930-06-21
I find this code clearer to read than the code doing divisions and modulo operations. It’s not as efficient, but for more than 19 out of 20 cases this should be no concern. If you like the divisions, you can of course do them with java.time too:
int year = intDate / 10000;
int monthDay = intDate % 10000;
int month = monthDay / 100;
int day = monthDay % 100;
LocalDate date = LocalDate.of(year, month, day);
If you do need a java.util.Date for a legacy API not yet upgraded to java. time (or Joda-Time), convert like this (no matter which of the above conversions you used):
Instant asInstant = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = Date.from(asInstant);
System.out.println(oldfashionedDate);
Output when my default time zone is set to Europe/Zaporozhye:
Sat Jun 21 01:00:00 EET 1930
(We notice that we get 01:00:00 because of transition to summer time (DST). The time of 00:00:00 didn’t exist on this day in this time zone.)
If still using Joda-Time
If you are still using Joda-Time, your own answer using toDateTimeAtStartOfDay() is just fine.
PS I reproduced your problem with Joda-Time 2.9.9, my time zone set to Europe/Zaporozhye and your integer of 19300621 (don’t know why you gave it as hex, 0x0126810d). I got an exception similar to yours: org.joda.time.IllegalInstantException: Illegal instant due to time zone offset transition (daylight savings time 'gap'): 1930-06-21T00:00:00.000 (Europe/Zaporozhye).
Link
Oracle tutorial: Date Time explaining how to use java.time.
I suggest the following:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
result = cal.getTime();
OK, finally got the following fragment and it works most close to my expectations. Like SDF but many times faster - like no string parsing just to get digits:
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
public static Date toDateJoda(int intDate) {
LocalDate ldt = new LocalDate(
intDate / 10000,
(intDate / 100) % 100,
intDate % 100);
DateTime dt = ldt.toDateTimeAtStartOfDay();
return dt.toDate();
}
Parses everything and gets next valid date / time for cases like mine.
OK, I think I managed to replicate your problem, by doing:
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Kiev"));
System.out.println( extract(0x0126810d));
(Previously I tried that with "EET", but apparently that gets a different time zone altogether)
I get an illegal argument exception, though the date it mentions is a bit different. This could be because of my version of Joda.
Illegal instant due to time zone offset transition (daylight savings time 'gap'): 1930-06-21T00:00:00.000 (Europe/Kiev)
Well, the way to solve it is not to be in the Europe/Kiev zone, at least for the sake of the Joda conversion:
public static Date extract(final int intDate) {
Date result = null;
DateTimeZone tz = DateTimeZone.forOffsetHours(2);
try {
result = new DateTime(
intDate / 10000,
(intDate / 100) % 100,
intDate % 100,
0,
0,
0,
0,
tz).toDate();
} catch (final IllegalArgumentException e) {
System.err.println(e.getMessage());
return null;
}
return result;
}
This would avoid the error. You could move the tz variable definition and initialization to a field if you wish to improve performance in case you are calling the extract method a lot of times.
Mind you that when you print the resulting Date object using the default date format, which in turn uses the default time zone (Europe/Kiev), the result would be:
Sat Jun 21 01:00:00 EET 1930
You can print it properly with:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
fmt.setTimeZone(TimeZone.getTimeZone("GMT+2"));
System.out.println(fmt.format( extract(0x0126810d)));
But maybe if you don't want to take DST into consideration, you should just work with the dates as if they were UTC. It depends what you want to do with them, really.
One last note: it's really easy to achieve the same result with Calendar:
public static Date extract2(final int intDate) {
cal.set(intDate / 10000, ( intDate / 100 ) % 100 - 1, intDate % 100);
return cal.getTime();
}
Where cal is a Calendar instance set in a field to avoid repeatedly creating and clearing it:
public static final Calendar cal;
static {
cal = Calendar.getInstance();
cal.clear();
}
(Mind multithreading, though).
Not sure about the performance problems you mentioned, and how critical the difference is.

String-Date conversion with nanoseconds

I've been struggling for a while with this piece of code for an Android app and I can't get the hang of it. I've read and tried every solution I found on stackoverflow and other places, but still no luck.
What I want to do is have a function to convert a string like "17.08.2012 05:35:19:7600000" to a UTC date and a function that takes an UTC date and converts it to a string like that.
String value = "17.08.2012 05:35:19:7600000";
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
try
{
Date today = df.parse(value);
System.out.println("Today = " + df.format(today) + " " + today.toGMTString());
}
catch (ParseException e)
{
e.printStackTrace();
}
This results in : Today = 17.08.2012 07:41:59:0000000 17 Aug 2012 04:41:59 GMT which are both wrong.
I tried setting SDF's timezone to UTC, no luck.
Another thing that I noticed: if I do df.setLenient(false);
It gives me : java.text.ParseException: Unparseable date: "17.08.2012 05:35:19:7600000" .
If anyone can provide me with some explanations / sample code, I would be very grateful. Thanks in advance
The result you are getting is absolutely right.
Let's analyze this:
17.08.2012 05:35:19:7600000
17: Day of month (17th)
08: Month of year (August)
2012: Year (2012)
05: Hour of day (5am)
35: Minute of hour (:35)
19: Second of minute (:19)
7600000: Milliseconds of second (7,600,000)
Now, the way the VM sees this is that you are declaring the time of day as 5:35:19am, then adding 7,600,000 milliseconds to it. 7,600,000 milliseconds = 7,600 seconds = 2 hours, 6 minutes, 40 seconds. 5:35:19am + 02:06:40 = 7:41:59am (and 0 milliseconds). This is the result you are getting. (It also appears that you are not setting the timezone properly, so the GMT string is 3 hours behind your result.)
If you want to retain the :7600000, to my knowledge this is not possible. As this can be simplified into seconds, the VM will automatically reduce it into the other time increments. The milliseconds (the SSSS) should be for storing values <1000.
I'd suggest you create a new SimpleDateFormat for your output; but remember that the milliseconds will be absorbed into the other times (since they are all stored as a single long in the Date object).
private String convertDate(String cdate)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
Date convertedDate;
try
{
convertedDate = dateFormat.parse(cdate);
cdate = postFormater.format(convertedDate);
}
catch (ParseException e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
}
return cdate;
}
Try this.
This is what you need (but it will loose millisecond information):
"dd.MM.yyyy HH:mm:ss.'000000'"
If you used "dd.MM.yyyy HH:mm:ss.SSSSSS", then would get three leading zeros for your milliseconds.
If you used "dd.MM.yyyy HH:mm:ss.SSS'000'", then you could format a date, but not parse any date.
Try it out:
public static void main(String[] args) throws ParseException {
printDate("dd.MM.yyyy HH:mm:ss.SSS");//02.05.2010 21:45:58.073
printDate("dd.MM.yyyy HH:mm:ss.SSSSSS");//02.05.2010 21:45:58.000073
printDate("dd.MM.yyyy HH:mm:ss.SSS'000'");//02.05.2010 21:45:58.073000
printDate("dd.MM.yyyy HH:mm:ss.'000000'");//02.05.2010 21:45:58.000000
tryToParseDate("dd.MM.yyyy HH:mm:ss.SSS");//good
tryToParseDate("dd.MM.yyyy HH:mm:ss.SSSSSS");//good
tryToParseDate("dd.MM.yyyy HH:mm:ss.SSS'000'");//bad
tryToParseDate("dd.MM.yyyy HH:mm:ss.'000000'");//good
}
private static void printDate(String formatString) {
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat(formatString);
String formattedDate = format.format(now);
// print that date
System.out.println(formattedDate);
}
private static void tryToParseDate(String formatString) {
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat(formatString);
String formattedDate = format.format(now);
// try to parse it again
try {
format.parse(formattedDate);
System.out.println("good");
} catch (ParseException e) {
System.out.println("bad");
}
}
To drop the nanoseconds, use:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.")
Update: java.time
The Question and other Answers use terrible date-time classes that are now legacy. These flawed classes were years ago supplanted by the modern java.time classes defined in JSR 310. Avoid Calendar, DateFormat, Date, etc.
Define a formatting pattern with DateTimeFormatter.
String input = "17.08.2012 05:35:19:7600000";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm:ss:SSSSSSS" );
Parse.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
A LocalDateTime object represents a date with a time of day, but lacks the context of a time zone or offset from UTC.
If you are certain the input text is intended to represent a moment as seen in UTC, having an offset of zero hours-minutes-seconds, then assign a ZoneOffset to produce an OffsetDateTime object.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
See this code run live at Ideone.com.
ISO 8601
I suggest you educate the publisher of your data about the use of ISO 8601 standard formats when serializing date-time values to text.
The java.time classes use ISO 8601 formats by default when parsing/generating text.

Check if 24 hours have passed (reading from a string)

I am saving date's in a file in the following format as a string.
Sat Jul 21 23:31:55 EDT 2012
How can I check if 24 hours have passed? I am a beginner so please explain it a little bit =)
I am not sure if I completely understood the question - do you have two dates for comparison or do you wish to keep checking periodically if 24 hours have elapsed?
If comparing two date/times, I would suggest looking at joda or perhaps date4j. Using joda, one could look into using interval between two dates:
Interval interval = new Interval(previousTime, new Instant());
where previous time would be the time you mentioned
You can do something like this:
try {
// reading text...
Scanner scan = new Scanner( new FileInputStream( new File( "path to your file here..." ) ) );
String dateString = scan.nextLine();
// creating a formatter.
// to understand the format, take a look here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
// EEE: Day name of week with 3 chars
// MMM: Month name of the year with 3 chars
// dd: day of month with 2 chars
// HH: hour of the day (0 to 23) with 2 chars
// mm: minute of the hour with 2 chars
// ss: second of the minute with 2 chars
// zzz: Timezone with 3 chars
// yyyy: year with 4 chars
DateFormat df = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US );
// parsing the date (using the format above, that matches with your date string)
Date date = df.parse( dateString );
// now!
Date now = new Date();
// gets the differente between the parsed date and the now date in milliseconds
long diffInMilliseconds = now.getTime() - date.getTime();
if ( diffInMilliseconds < 0 ) {
System.out.println( "the date that was read is in the future!" );
} else {
// calculating the difference in hours
// one hour have: 60 minutes or 3600 seconds or 3600000 milliseconds
double diffInHours = diffInMilliseconds / 3600000D;
System.out.printf( "%.2f hours have passed!", diffInHours );
}
} catch ( FileNotFoundException | ParseException exc ) {
exc.printStackTrace();
}
I would suggest storing your information as a java.util.Calendar which has a compareTo ()function.
If you want to compare now to current time, you can use System.getCurrentTimeMillis() to get the current time.
Define A Day
Do you really mean one day or 24-hours? Because of Daylight Saving Time nonsense, a day can vary in length such as 23 or 25 hours in the United States.
Avoid 3-Letter Time Zone Codes
That String format is a terrible representation of a date-time. It is difficult to parse. It uses a 3-letter time zone code, and such codes are neither standardized nor unique. If possible, choose another format. The obvious choice is ISO 8601, for example: 2014-07-08T04:17:01Z.
Use proper time zone names.
Avoid j.u.Date & .Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Instead use either the venerable Joda-Time library or the new java.time package bundled in Java 8 (and inspired on Joda-Time).
Joda-Time
Here is some example code in Joda-Time.
Get the current moment.
DateTime now = DateTime.now();
Parse the input string.
String input = "Sat Jul 21 23:31:55 EDT 2012";
DateTime formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss zzz yyyy" ).with Locale( java.util.Locale.ENGLISH );
DateTime target = formatter.parseDateTime( input );
Calculate 24 hours (or next day).
DateTime twentyFourHoursLater = target.plusHours( 24 );
Test if current moment happened after.
boolean expired = now.isAfter( twentyFourHoursLater );
Or, if you want next day rather than 24-hours, use plusDays rather than plusHours. If necessary, adjust to desired time zone. Time zone is crucial as it defines the day/date and applies rules for anomalies such as Daylight Saving Time.
DateTime targetAdjusted = target.withZone( DateTimeZone.forID( "Europe/Paris" ) );
…
DateTime aDayLater = targetAdjusted.plusDays( 1 ); // Go to next day, accounting for DST etc.
boolean expired = now.isAfter( aDayLater ); // Test if current moment happened after.

Unix epoch time to Java Date object

I have a string containing the UNIX Epoch time, and I need to convert it to a Java Date object.
String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
Date expiry = df.parse(date);
} catch (ParseException ex) {
ex.getStackTrace();
}
The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat().
How about just:
Date expiry = new Date(Long.parseLong(date));
EDIT: as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:
Date expiry = new Date(Long.parseLong(date) * 1000);
Epoch is the number of seconds since Jan 1, 1970..
So:
String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );
For more information:
http://www.epochconverter.com/
java.time
Using the java.time framework built into Java 8 and later.
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]
In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.
ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
long timestamp = Long.parseLong(date)
Date expiry = new Date(timestamp * 1000)
Better yet, use JodaTime. Much easier to parse strings and into strings. Is thread safe as well. Worth the time it will take you to implement it.
To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.
long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)
Hum.... if I am not mistaken, the UNIX Epoch time is actually the same thing as
System.currentTimeMillis()
So writing
try {
Date expiry = new Date(Long.parseLong(date));
}
catch(NumberFormatException e) {
// ...
}
should work (and be much faster that date parsing)

Categories