date is null and crashing on a few devices - android

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

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.

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())

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();
}

Related

Android DateFormatter print Eastern Daylight Time instead of EDT

So Im trying to print the string "Eastern Daylight Time" instead of EDT . This should be dynamic and not hardcoded. Looking into DateFormatter class did not lead me to an answer that worked.
Here was an example that allows me to format but did not lead me to my specific answer.
I am getting the date back in the following format -
2013-06-08T00:00:00-04:00
Here are somethings that I have tried -
1)
String dateString = changeFormatDateStringWithDefaultTimeZone(paymentConfirmation.getTransactionDate(),
"yyyy-MM-dd'T'HH:mm:ssZ",
"M/d/yyyy hh:mm a zz");
public static String changeFormatDateStringWithDefaultTimeZone(String value, String ip_format, String op_format) {
if (value == null)
return null;
try {
SimpleDateFormat opSDF = new SimpleDateFormat(op_format, Locale.US);
opSDF.setTimeZone(TimeZone.getDefault());
SimpleDateFormat inSDF = new SimpleDateFormat(ip_format, Locale.US);
Date date = inSDF.parse(value);
return(opSDF.format(date));
} catch (Exception e) {
Log.e("Err", "Failed to convert time "+value);
e.printStackTrace();
}
return null;
}
2)
Date today = Calendar.getInstance().getTime();
String todayString = DateUtils.convertDateToStringWithTimeZone(today);
public static String convertDateToStringWithTimeZone(Date date){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = df.format(date);
dateString += " " + TimeZone.getDefault().getDisplayName(false, TimeZone.LONG);
return dateString;
}
These always print timezone as EDT and I want the string Eastern Daylight Time. Can anyone help me out with this?
Okay, based on your last edit of the question, the solution should be like this:
case 1)
The output pattern should be changed to "M/d/yyyy hh:mm a zzzz" (note the count of z-symbols to enforce the full zone name). Depending on the date and the underlying timezone, the formatter SimpleDateFormat will automatically determine if the daylight or the standard name is to be used.
case 2)
Use TimeZone.getDefault().getDisplayName(true, TimeZone.LONG) to enforce the long daylight name. If your default timezone is "America/New_York" then such an expression should print "Eastern Daylight Time". Note that the boolean parameter has been changed to true.

Datetime conversion one timezone to another timezone in Android

I stuck with timezone conversion can any one help me to get out of it
My code for time conversion is below
public static String convertToLocalTimeZone(String date, String timeZone)
{
SimpleDateFormat df1 = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
df1.setTimeZone(TimeZone.getTimeZone(timeZone));
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone(timeZone));
try {
calendar.setTime(df1.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat df2 = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
df2.setTimeZone(TimeZone.getDefault());
calendar.setTimeZone(TimeZone.getDefault());
return df2.format(calendar.getTime());
}
Parameter timeZone is America/New_York and expected is Asia/Calcutta
I'm getting two different string for datetime and time zone now I have to convert datetime according to device local timezone
I have used Joda-Time and with some modification I have implemented and fixed my issue.

Date and time to milliseconds in Android

I am trying to convert given date and time to milliseconds. I am not able to achieve it.
Below is the format of date and time
02 - 07 (DD - MM)
08:50:00 AM (hh mm ss a)
Here is what I have tried:
String myDate = "2-05";
String myTime = "08:50:00";
String ampm = "AM";
String toParse = myDate + " " + myTime+" " + ampm;
try
{
SimpleDateFormat formatter3 = new SimpleDateFormat("d-M hh:mm:ss a"); // I assume d-M, you may refer to M-d for month-day instead.
Date date;
date = formatter3.parse(toParse);
long millis = date.getTime();
Log.e ("Date in milli",""+millis);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} // You will need try/cat
Below is the error I am getting:
08-04 16:50:34.368: W/System.err(6603): java.text.ParseException: Unparseable date: "2-05 08:50 AM"
08-04 16:50:34.368: W/System.err(6603): at java.text.DateFormat.parse(DateFormat.java:626)
Not sure where I am going wrong? Can somebody help me out ?
Thanks!
There is a difference between the exception you're getting and the date you're supplying in the code. The exception says the provided string is 2-05 08:50 AM, but you should be providing the seconds field as well. It should be 2-05 08:50:00 AM is there a mismatch somewhere? Are you running old code?
As others have identified, if your month is always two digits, you need to use MM instead of M

Android Date format conversion 71

I have a date in 02/21/2013 04:52:10 PM this format.
How do I convert it into MM-dd-yyyy HH:mm. I already tried few things but it keeps throwing error
java.text.ParseException: Unparseable date: "02/21/2013 04:52:10 PM" (at offset 2)
I really need a help from date format expert.
Thanks
Try this one:
DateFormat inputFormat = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a", Locale.getDefault());
DateFormat outputFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm", Locale.getDefault());
try {
System.out.println("Converted: " + outputFormat.format(inputFormat.parse("02/21/2013 04:52:10 PM")));
} catch (ParseException e) {
e.printStackTrace();
}
Output: 01-21-2013 16:52
Checkout http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html for more
Cheers
Construct two SimpleDateFormat objects. The first you parse() the value from into a Date object, the second you use to turn the Date object back into a string, e.g.
try {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
return df2.format(df1.parse(input));
}
catch (ParseException e) {
return null;
}
Parsing can throw a ParseException so you would need to catch and handle that.
In addition, check this out:-
http://developer.android.com/reference/java/text/SimpleDateFormat.html
and more:-
http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx
and more:-
Date format conversion Android
You need verify if your String have / or - in the mask, case have / then you must used:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", LOCALE_BR);
Date convert = sdf.parse(data);
case your String have - then you must used:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", LOCALE_BR);
Date convert = sdf.parse(data);
Or then, use the replace() for change of the caracter - for /

java.text.ParseException: Unparseable date: 2010-12-10 17:18:3600

i'm getting this exception when i try to parse a date that i get from a SQL database, the date is a datetime on the sql and i recive it as a String with JSON, and seeing the excepcion i think that the string i recived is like this:2010-12-10 17:18:3600
this is the exception i get:
java.text.ParseException: Unparseable date: 2010-12-10 17:18:3600
i use the next code to parse the date (i get it from google) but it gets the exception
How can i modify this code to get the parse working???? please guive me the answer with code, date parsing and using of simpledateformat it's very hard for me
public void setPositiontime(String positiondate)
{
SimpleDateFormat FORMATTER = new SimpleDateFormat("d MMM yyyy HH:mm");
// pad the date if necessary
while (!positiondate.endsWith("00")){
positiondate += "0";
}
try {
this.positiondate = FORMATTER.parse(positiondate.trim());
} catch (ParseException e) {
throw new RuntimeException(e);
}
i get the error on this line: this.positiondate = FORMATTER.parse(positiondate.trim());
Try this
SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
It is simply a representation of what each digit in the format means so its:
Years-months-date hour:min:milli

Categories

Resources