Trying to parse a date throws parser error - android

Im trying to parse date of type 23-May-2016 and 24-May 2016 for instance..
Following code demonstrates how im parsing the date.
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
Date validityDate = null;
Date nextDueDate = null;
try {
validityDate = format1.parse(mValidityDate.getText().toString());
nextDueDate = format1.parse(mNextDueDate.getText().toString());
int validate = validate(validityDate, nextDueDate);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(),Toast.LENGTH_SHORT).show();
}
Following is the code that finds the number of difference between two dates.
public static int validate(Date valid, Date nextDueDate) {
return (int) ((nextDueDate.getTime() - valid.getTime()) / (1000 * 60 * 60 * 24l));
}
The problem is that, im getting Date parser error at offset 3. Why is that so?

You need to use two different SimpleDateFormat
For date 23-May-2016 you need new SimpleDateFormat("dd-MMM-yyyy");
For date 24-May 2016 you need new SimpleDateFormat("dd-MMM yyyy");

You are using the pattern "dd-MM-yyyy" which means you're trying to parse a date of the form 12-05-2016.
If you need to parse a date such as "12-May-2016", then you have to use 3M letters for the month as follows. "dd-MMM-yyyy".
However, this will output "12-Jun-2016", if you parse the date "12-06-2016".
If you need the complete month, then you should use 4M letters. E.g: "dd-MMMM-yyyy". Then it will output 12-June-2016.

Related

How to not convert Date and time to any time zone

I am accessing Dot net web services and using Ksoap library as my web services are Soap based.
Basically i want to save the dates and show them in list at it is. I do not want the date conversion to any specific region or time zone.
my dates which are coming from services has following pattern please have an example of threee different fields.
patient DOB = 1974-05-18T00:00:00
Collection Date = 2016-07-27T11:00:00
attachment Date uploaded = 2016-09-28T10:19:23.48
and I am using following method to convert them
public static Date convertStringToDate(String date,String dateFormat)throws Exception {
Date output = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
output = simpleDateFormat.parse(date);
} catch (ParseException e) {
throw e;
}
return output;
}
where dateFormat is "yyyy-MM-dd" and whereas date could be any string shown above in above example.
Problems:
1> When I convert date using that method I sometimes get accurate time and date
2> Some times I observed slightly changed in time , like 2 to 7 hours shift in time. this is due to time zone conversion
3> Some times I observe a whol day shift. Let suppose if the date that was coming from server was 2016-09-28T10:19:23.48 after conversion it becomes 2016-09-27 to me .
Whats wrong ? How can I simple show date as it is from web services How can i get that except saving dates directly in strings and showing those strings by splitting.
Please help me.
Update
i am converting back my date object back to string to show on UI in following manner
public static String convertDateToString(Date date,String dateFormat)throws Exception {
String output = "";
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
output = simpleDateFormat.format(date);
} catch (Exception e) {
throw e;
}
return output;
}
To achieve that, you need to know the actual timezone and dateformat of the server. If you knew it already, the following snippet would be useful
public static String parseDateFormat(String incomingDate, String inputFormat, String outputFormat) {
String finalDate = null;
SimpleDateFormat input = new SimpleDateFormat(inputFormat); // server date format
input.setTimeZone(TimeZone.getTimeZone(SERVER_TIMEZONE)); // timezone set in the server
SimpleDateFormat output = new SimpleDateFormat(outputFormat); // format to which you want to convert
output.setTimeZone(Constants.UTC_TIMEZONE); // timezone to which you want to convert
try {
Date realDate = input.parse(incomingDate);
finalDate = output.format(realDate);
} catch (ParseException e) {
Log.e("Error", e.getMessage(),e);
}
return finalDate;
}
Setting the time zone on the date format adds an offset to the time stamp. And your server's time format doesn't include any time zone.
Remove the line simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
You generally need to set the time zone only when you intend to account for the difference between locales.

How to convert time as per Timezone selection in android?

My Application downloading shopping details.
Example :
Shopping details downloaded at 5 :30 London time.
Now, change any other timezone, so convert downloaded time s per the selected timezone.
Timezone is changing from settings under Date/time.
How to programmatically achieve this ?
so how to convert the downloaded time as per the timezone selection ?
Try this,
I assume you have downloaded the shopping details at 12:00 PM London time. I am using HH assuming that you are using 24hr format. If you want to convert that to device default time zone, set the timezone using DateFormat & format the existing time.
TimeZone.getDefault() which gives the device default timezone.
try {
DateFormat utcFormat = new SimpleDateFormat("HH:mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = utcFormat.parse("12:00");
DateFormat deviceFormat = new SimpleDateFormat("HH:mm");
deviceFormat.setTimeZone(TimeZone.getDefault()); //Device timezone
String convertedTime = deviceFormat.format(date);
} catch(Exception e){
}
no, there are no APIs for changing time or timezone.. It is not possible to change the phone's timezone programmatically.
Based on #Raghavendra solution, this can be a portable method as follows:
/**
* converts GMT date and/or time with a certain pattern into Local Device TimeZone
* Example of dateTimePattern:
* "HH:mm",
* "yyyy-MM-dd HH:mm:ss",
* "yyyy-MM-dd HH:mm"
* Ex of dateTimeGMT:
* "12:00",
* "15:23",
* "2019-02-22 09:00:21"
* This assumes 24hr format
*/
#SuppressLint("SimpleDateFormat")
private String getDeviceDateTimeFromGMT(String dateTimePattern, String dateTimeGMT) {
try {
DateFormat utcFormat = new SimpleDateFormat(dateTimePattern);
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // convert from GMT TimeZone
Date date = utcFormat.parse(dateTimeGMT);
DateFormat deviceFormat = new SimpleDateFormat(dateTimePattern);
deviceFormat.setTimeZone(TimeZone.getDefault()); // Device TimeZone
return deviceFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Usage:
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm", "2019-02-22 16:07");
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm:ss", "2019-02-22 16:07:13");
getDeviceDateTimeFromGMT("H:mm", "16:07");

How to covert string data like 2016-4-10 00:00:00 to timestamp?

I want convert data like 2016-4-10 00:00:00 to timestamp.
I use this code (I send this date as argument to this method):
public static long parseUTimeAndGiveTimestamp(String time) {
if (time != null && !time.equals("")) {
long longTime = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS");
Date date;
try {
time += ".000";
date = sdf.parse(time);
} catch (Exception e) {
e.printStackTrace();
return longTime;
}
longTime = date.getTime();
return longTime / 1000;
}
return 0;
}
But I get 1460235600 value and if I convert it to date again I get:
Sat, 09 Apr 2016 21:00:00
(before 10.04 - after 09.04)
So you can help me?
There is no issue with your code. There is some issue with the timezones. Your SimpleDateFormat will be using your local timezone. You probable might be getting the timestamp for your locale and while converting it back to the date, you are checking in GMT timezone. To test this just add
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
before parsing the date.
So basically you are not using the same timezones to convert date to timestamp and while converting timestamp to zone.
try to use one M to parse single-digit month format. It also handles two-digits correctly...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd kk:mm:ss.SSS");

Regading about JSON data parsing in Android

I am using openweather API for calling current location.In JSON parsing, I saw "dt": 1457852143 (UTC/unix) http://openweathermap.org/weather-data which means last updated.So in my app, I stored that value in String variable String last_update=total.getString("dt") where total holding the full JSON data.I ran my app and got the output as 1457852143 on screen.Although I wanted it to show in local time but I am unable to convert.
I am using Android Studio 1.5.Any suggestion would be highly appreciated.
I've used the following before to do this. This is using the Date class but I've heard it's better to use the Calendar class. This should get you in the right direction though.
public static String convertUTCtoLocalTime(String p_city, String p_UTCDateTime) throws Exception{
String lv_dateFormateInLocalTimeZone="";//Will hold the final converted date
Datelv_localDate = null;
Stringlv_localTimeZone ="";
SimpleDateFormat lv_formatter;
SimpleDateFormat lv_parser;
//Temp for testing(mapping of cities and timezones will eventually be in a properties file
if(p_city.equals("LON")){
lv_localTimeZone="Europe/London";
}else if(p_city.equals("NBI")){
lv_localTimeZone="EAT";
}else if(p_city.equals("BRS")){
lv_localTimeZone="Europe/Brussels";
}else if(p_city.equals("MNT")){
lv_localTimeZone="America/Montreal";
}else if(p_city.equals("LAS")){
lv_localTimeZone="PST";}
//create a new Date object using the UTC timezone
lv_parser = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
lv_parser.setTimeZone(TimeZone.getTimeZone("UTC"));
lv_localDate = lv_parser.parse(p_UTCDateTime);
//Set output format - // prints "2007/10/25 18:35:07 EDT(-0400)"
lv_formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z'('Z')'");
System.out.println("convertUTCtoLocalTime "+p_city+": "+ "The Date in the UTC time zone(UTC) " + lv_formatter.format(lv_localDate));
//Convert the UTC date to Local timezone
lv_formatter.setTimeZone(TimeZone.getTimeZone(lv_localTimeZone));
lv_dateFormateInLocalTimeZone = lv_formatter.format(lv_localDate);
System.out.println("convertUTCtoLocalTime: "+p_city+": "+"The Date in the LocalTime Zone time zone " + lv_formatter.format(lv_localDate));
return lv_dateFormateInLocalTimeZone;
}

Getting number of days difference between 2 dates

I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas
To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}

Categories

Resources