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;
}
Related
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.
I'm developing an app in which I'm saving the time when the post was posted.
I'm getting that time by using this code:
DateFormat currentTime = new SimpleDateFormat("h:mm a");
final String time = currentTime.format(Calendar.getInstance().getTime());
Now, what I want is I want to get user's timezone and convert the time saved in database using his/her timezone to his/her local time.
I tried doing this using code:
public String convertTime(Date d) {
//You are getting server date as argument, parse your server response and then pass date to this method
SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a");
String actualTime = sdfAmerica.format(d);
//Changed timezone
TimeZone tzInAmerica = TimeZone.getDefault();
sdfAmerica.setTimeZone(tzInAmerica);
convertedTime = sdfAmerica.format(d);
Toast.makeText(getBaseContext(), "actual : " + actualTime + " converted " + convertedTime, Toast.LENGTH_LONG).show();
return convertedTime;
}
but this is not changing the time.
This is how I'm trying to convert time saved in database using above method (postedAtTime is the time which is getting retrieved from database):
String timeStr = postedAtTime;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
Date date = null;
try {
date = df.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
convertTime(date);
Please let me know what's wrong in my code or if this is wrong way?
The time string you're storing is not sufficient to be able to change timezones after the fact (h:mm a is only hours, minutes and am/pm marker). In order to do something like this you need to either store the timezone the original timestamp was in or better yet store the time in a deterministic manner like always UTC.
Example code:
final Date now = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
// Convert to UTC for persistence
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Persist string to DB - UTC timezone
final String persisted = sdf.format(now);
System.out.println(String.format(Locale.US, "Date is: %s", persisted));
// Parse string from DB - UTC timezone
final Date parsed = sdf.parse(persisted);
// Now convert to whatever timezone for display purposes
final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US);
displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
final String display = displayFormat.format(parsed);
System.out.println(String.format(Locale.US, "Date is: %s", display));
Output
Date is: 2016-06-24 17:49:43
Date is: 13:49 PM -0400
In my Android application I need to get date of a picture from Instagram api. Instagram return some value from created_time tag which not in milliseconds format. If I convert that value to date, java return invalid date. How can I get correct date from the "created_time" tag?
Instagram return the date in Unix time stamp so that I got invalid date while converting. The solution is we need to multiple 1000 with created_time tag value.
This is the code:
String x = "1414678736"; // created_time tag value goes here.
long foo = **Long.parseLong(x)*1000;**
Date date = new Date(foo);
DateFormat formatter = new SimpleDateFormat("MMMM dd,yyyy");
System.out.println(formatter.format(date));
I have stored date in database,
first take the current date then convert it into String then store it into database,
it is working fine.
Then I want to retrieve the data and show it to ListView,
for that i did:
// get the string value of date
String dateString = c.getString(c.getColumnIndex(CallHistoryDataBase.colDate));
// format according to system's current format
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
textViewDateTime.setText(dateFormat.format(new Date(dateString)));
It is working fine,
like if I have stored date with "dd/MM/yyyy" format
and later I have changed the System's format to "yyyy/MM/dd"
in list it showing with "yyyy/MM/dd" format.
But some time it displays 2014/04/14 for date 2012/04/14.
I have checked, at the time of storing and retrieving data to and from database it is fine.
I don't get any clue. There is no hard code, not even 14 number is there.
Any suggestion...
different solution is also acceptable.
public String getDate(final Context context, final long time) {
long t = time;
if (t < MIN_DATE) {
t *= MILLIS;
}
final Calendar base = Calendar.getInstance();
base.set(Calendar.HOUR_OF_DAY, 0);
base.set(Calendar.MINUTE, 0);
base.set(Calendar.SECOND, 0);
if (t < base.getTimeInMillis()) {
SimpleDateFormat df1 = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate1 = df1.format(t);
return formattedDate1;
// return DateFormat.getDateFormat(context).format(t);
} else {
return DateFormat.getTimeFormat(context).format(t);
}
}
by using this method you can get date in dd-mm-yyyy formate.And pass data in database as millisecond time.
Hope its useful for you.
I want to convert date time object in java to json string in format as below:
{"date":"/Date(18000000+0000)/"}
I did like this but it didn't give me the format i desired:
JSONObject object = new JSONObject();
object.put("date",new Date());
and the result of object.toString()
{"date":"Fri May 04 11:22:32 GMT+07:00 2012"}
i want the string "Fri May 04 11:22:32 GMT+07:00 2012" transform to "/Date(18000000+0000)/" (18000000+0000 here is just a example).
Thanks for your help.
Here is my solution, although it is not a good way, but I finally find a workable solution.
SimpleDateFormat format = new SimpleDateFormat("Z");
Date date = new Date();
JSONObject object = new JSONObject();
object.put("date", "/Date(" + String.valueOf(date.getTime()) + format.format(date) + ")/");
public static String convertToJsonDateTime(String javaDate)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date currentDate = null;
try {
currentDate = dateFormat.parse(javaDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long time =currentDate.getTime();
return "\\/Date("+time+"+0000)\\/";
}
My solution : I think this is the simplest Way
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
yourJsonObject.accumulate("yourDateVarible",dateFormat.format(new Date()));
The date format that you want is /Date(<epoch time><Time Zone>)/.
You can get the epoch time in java using long epoch = System.currentTimeMillis()/1000;(found at this link) and the time zone you can get by using the date and time patteren as Z. Then combine all the strings into one and store it to the Json Object.
Other possibility is that the time you are getting from iOS device may be of the pattern yyMMddHHmmssZ as got from here. Check the output on the iOS device at different times and identify the correct pattern.
From json.org's description of JSONObject:
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
This library doesn't support the "complex" mapping of a Date to a JSON representation. You'll have to do it yourself. You may find something like SimpleDateFormat helpful.
If your format like this -> "DDmmYYYY+HHMM"
DD -> Day (2 Digit)
mm -> Month (2 Digit)
YYYY -> Year (4 Digit)
HH -> Hour
MM -> Minute
Than you can do like this:
SimpleDateFormat format = new SimpleDateFormat("DDmmYYYY+HHMM");
JSONObject object = new JSONObject();
object.put("date", "/Date(" + format.format(new Date()) + ")/");
I suppose that's a representation of ISO international date-time format.
YYYYMMDD+HHMM
I think now you will be able to create that string
may be like,
Date d=new Date();
String tmp="";
tmp="/Date("d.getYear()+""+d.getMonth()+""+d.getDate()+"+"+d.getHours()+""+d.getMinutes()+")/";
Upgrade one of the previous answer:
public static String convertToJsonDateTime(Date dateToConvert) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
long time = dateToConvert.getTime();
return "/Date(" + time + "+0000)/";
}