0

What I have

I have a server date in w3c date format 2016-02-13T09:53:49.871Z for notification

What I want

I wanted to convert the w3c format to device time zone then get the current date from the device to check whether sever date is equal to device date

My problem

I get Parse error: 2016-03-10 15:45:36 at Date formattedServerDeviceDate=new Date(serverDateDeviceFormat);

My code

public boolean isTodaysNotification(String serverDate)throws Exception{
        boolean isTodaysNotification=false;
        SimpleDateFormat simpleDateFormatW3C = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
        simpleDateFormatW3C.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date dateServer = simpleDateFormatW3C.parse(serverDate);

        TimeZone deviceTimeZone = TimeZone.getDefault();
        SimpleDateFormat simpleDeviceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDeviceFormat.setTimeZone(deviceTimeZone);
        String serverDateDeviceFormat = simpleDeviceFormat.format(dateServer);

        Date formattedServerDeviceDate=new Date(serverDateDeviceFormat); // formatted to device time zone (w3c to utc)


        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd"); // formatting  to consider only  "yyyy-MM-dd"
        String strServerDate=simpleFormat.format(formattedServerDeviceDate); // server date
        String strTodaysDate=simpleFormat.format(new Date()); // current date

        if (new Date(strTodaysDate).compareTo(new Date(strServerDate))==0){
            isTodaysNotification=true;
        }
        else {
            isTodaysNotification=false;
        }
        return  isTodaysNotification;
    }
karthik kolanji
  • 2,044
  • 5
  • 20
  • 56
  • string-arg `Date` constructor accepts representation in many formats, but not one that you offer. Use `Date d = simpleDeviceFormat.parse(...)` instead – Alex Salauyou Mar 10 '16 at 12:03

3 Answers3

4

The string-based constructor of java.util.Date expects a string in a format produced by the method toString(). Something like "Sat, 12 Aug 1995 13:30:00 GMT+0430".

See also the description of parser in question. Advise: Don't use deprecated stuff.

Most important: You cannot get a formatted instance of java.util.Date. This object does not carry any format information but is just a wrapper around a long value. So your try to "format" the date-object is wrong. Just continue to use the dateServer. It is the same value around the globe.

How to help?

You can - of course - convert a Date-object to a Calendar-object and ask that for year, month, day. Example:

GregorianCalendar gcal = new GregorianCalendar(TimeZone.getDefault());
java.util.Date serverDate = new Date(); // here for demonstration, use that from server
gcal.setTime(serverDate);
int year = gcal.get(Calendar.YEAR);
int month = gcal.get(Calendar.MONTH) + 1;
int dayOfMonth = gcal.get(Calendar.DAY_OF_MONTH);

But here the general problem starts: In order to make a date-only-comparison, you need to know the timezone of server to apply the same procedure and compare the date components (year, month, day-of-month). And even if you know the timezone of the server, does this make sense? Why should clients care about server internals?

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • *expects a string in a format produced by the method toString()*--not exactly, doc says there are many formats it works with – Alex Salauyou Mar 10 '16 at 12:08
  • 1
    @SashaSalauyou Yes but it does NOT understand w3c- or ISO-8601-format. But the main problem is: The OP tries to "format" the date-object. – Meno Hochschild Mar 10 '16 at 12:12
  • I cant compare the value of dateServer , because it also has hours,minutes and seconds I only need "yyyy-MM-dd" to compare whether it is today – karthik kolanji Mar 10 '16 at 12:16
  • @MenoHochschild yes, I see, I just say that other formats except `toString()`-like are accepted. – Alex Salauyou Mar 10 '16 at 12:19
  • @karthikkolanji Sorry no. The `dateServer`-object has itself no hour etc. (formally yes, but only related to default time zones via deprecated methods). You have to convert it to a `GregorianCalendar` to be able to ask for zone-related hour, minute etc. Or use external libraries like ThreetenABP, Joda-Time, Time4A to use dedicated calendar-date-types. – Meno Hochschild Mar 10 '16 at 12:21
0

Try this approach: using simpleDeviceFormat.parse(...) instead of new Date(String)

From String to Date

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date formattedServerDeviceDate = format.parse(serverDateDeviceFormat);  
    System.out.println(formattedServerDeviceDate);  
} catch (ParseException e) {  
    e.printStackTrace();  
}
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
  • I didn't got this . sorry – karthik kolanji Mar 10 '16 at 12:04
  • I am getting value in serverDateDeviceFormat , but trying to convert to date object I get error – karthik kolanji Mar 10 '16 at 12:05
  • 1
    @karthikkolanji you're trying to get date using `Date` string constructor, which doesn't understand format you offer. – Alex Salauyou Mar 10 '16 at 12:07
  • I wanted the server date and device current date to be in format "yyyy-MM-dd" to compare – karthik kolanji Mar 10 '16 at 12:11
  • @karthikkolanji there is no format kept inside `Date`, so by using `yyyy-MM-dd` you just get output with omitted time value, but `Date` instance still holds time value. To compare dates, convert both dates to `Calendar` and use its `get(Calendar.YEAR)` and `get(Calendar.DAY_OF_YEAR)` methods. – Alex Salauyou Mar 10 '16 at 12:15
  • @karthikkolanji You need to understand that the `java.util.Date`-object you get from server is also the same on the device. Only the formatted text representations are different due to different zones. – Meno Hochschild Mar 10 '16 at 12:16
  • let me try your Calendar idea – karthik kolanji Mar 10 '16 at 12:18
  • @MenoHochschild by "equal date" OP means equality of only date part in current TZ I believe. – Alex Salauyou Mar 10 '16 at 12:18
  • @karthik kolanji: You said your problem is `Parse Error` and I proposed a possible solution. Is that what you want? If you want better answer, try to update your question! – T D Nguyen Mar 10 '16 at 12:19
  • @karthikkolanji this is not exactly my idea. http://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion – Alex Salauyou Mar 10 '16 at 12:21
0

Assuming you need to check if datetime, represented as a String at UTC timezone, belongs to current day in default timezone:

public boolean isToday(String utcDatetime, String format) throws Exception {
    DateFormat sdf = new SimpleDateFormat(format);
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    Calendar c1 = Calendar.getInstance();        // calendar with default TZ
    Calendar c2 = Calendar.getInstance();
    c1.setTime(sdf.parse(utcDatetime);           // input datetime
    c2.setTime(new Date());                      // current datetime
    return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
        && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR);
}
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67