2

I am using the this code to convert date time to unixtime gmt . It is working fine on most of the devices but it is crashing in a few . I am unable to determine the cause. How can I fix it ?

int gmtOffset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
        String dt="11-01-2016 5:8 AM";
        DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = null;
        try {
            date = format.parse(dt);
            System.out.println("Date ->" + date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long unixtime = (date.getTime() -(gmtOffset))/1000;

error:

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
jason
  • 3,932
  • 11
  • 52
  • 123

3 Answers3

6

When the locale is not set to US English, the locale's Am/pm marker may be different. For example, in Chinese, the AM/PM maker will be 上午/下午.

Thus, to force use of AM/PM, you'd need to use a US date format:

DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.US)

I ran this code when in the US locale, and it worked fine. When I switched to Chiense, I got the message:

java.text.ParseException: Unparseable date: "11-01-2016 5:8 AM" (at offset 15)

Offset 15 is the AM/PM marker. Thus, when exiting the try/catch block, the date object will remain null, causing the NullPointerException when calling the getTime() method.

By the way, you might consider using Joda DateTime to get the Unix epoch, something along the lines of: Joda DateTime to Unix DateTime.

Community
  • 1
  • 1
CJBS
  • 15,147
  • 6
  • 86
  • 135
0

Maybe the dtStart doesn't have the same format always (in this case it is hardcoded). If the format of dtStart is not correct after try catch block "date" is null and the app crashes at the last line because the date is null. (date.getTime())

David Rauca
  • 1,583
  • 1
  • 14
  • 17
0

The exception is throw when date is null. And date will be null if dtStart can't be parsed. Try like this:

int gmtOffset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
String dtStart="11-01-2016 5:8 AM";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
long unixtime = 0;
try {
    date = format.parse(dtStart);
    System.out.println("Date ->" + date);
    unixtime = (date.getTime() -(gmtOffset))/1000;
} catch (Exception e) {
    e.printStackTrace();
}
Federico Picci
  • 1,105
  • 10
  • 17