2

Here is my string:

2015,10,10,4,22,51

How can I convert this string to timestamp such as:

1447125771290

to compare with

long currentTime = System.currentTimeMillis();

Or any suggestions to compare with current system time?

linhtruong
  • 441
  • 3
  • 12
  • timestamps don't have timezone. 1447208700000 is 02:25 GMT the 11/11/2015 (your server is lying) – njzk2 Nov 11 '15 at 03:54
  • hmm actually I set time at 03:25 in GMT+0 and send to server. So how can I handle this string: LocalDate(2015,10,11,3,25,0) to Date and compare to current time? I mean something not manually such as compare each hours, minutes, .... – linhtruong Nov 11 '15 at 04:00
  • it looks like the issue is that the time on your server is wrong. – njzk2 Nov 11 '15 at 04:10
  • I think so, maybe I should get the value of LocalDate and find solution to compare with currentTime – linhtruong Nov 11 '15 at 04:22
  • 1
    These answers definitely have all you need: 1. http://stackoverflow.com/questions/9682891/how-to-convert-datetime-to-timestamp-in-java 2. http://stackoverflow.com/questions/18915075/java-convert-string-to-timestamp – Dut A. Nov 11 '15 at 05:14

1 Answers1

2

I think this would help you:

String timestamp = "2015,10,10,04,22,51";
DateFormat df = new SimpleDateFormat("yyyy,MM,dd,hh,mm,ss");
Date parsedDate = df.parse(timestamp);

And compare it with current date:

DateFormat dateFormat = new SimpleDateFormat("yyyy,MM,dd,hh,mm,ss");
Date date = new Date();

And here is how to compare:

public Date compareTime(Date date) {    
Calendar cal = Calendar.getInstance();  
cal.setTime(date);  
cal.set(Calendar.HOUR_OF_DAY, 0);  
cal.set(Calendar.MINUTE, 0);  
cal.set(Calendar.SECOND, 0);  
cal.set(Calendar.MILLISECOND, 0);  
return cal.getTime(); 
}

And the use above method like this:

if (compareTime(parsedDate).equals(date)

Another way to compare dates using Date class:

switch (date.compareTo(parsedDate)) {
case -1:  Log.i("CompareDates","today is sooner than parsedDate");  break;
case 0:   Log.i("CompareDates","today and parsedDateare equal");  break;
case 1:   Log.i("CompareDates","today is later than parsedDate");  break;
default:  Log.i("CompareDates","Invalid results from date comparison"); break;
}
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78
  • except no, because as you can see in the question, the month value 10 is november, it appears the server uses the same 0-basd numbering for months as java does. Meaning a/ you can have a 0 value that will not be correctly parsed, b/ you need to add 1 to all other cases. – njzk2 Nov 11 '15 at 14:13