Convert DateTime object java to Json string - android

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)/";
}

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.

How to get local time Android

I have a String of a date and time in my app eg:- 2014-10-30T11:30:00 I want to convert this String into my local time which should look something like this
2014-10-30T11:30:00+05:30. I cannot Manipulate the String as the server side conversion is done to do the addition and subtraction of the time. How do I add the +05:30 offset to my time?
How can I do it using the local time so that the server knows my locale?
Try this way,hope this will help you to solve your problem.
How to use given function :
convertDateStringFormat("2014-10-30T11:30:00","yyyy-MM-dd'T'hh:mm:ss","yyyy-MM-dd'T'hh:mm:ss")
Here you have pass three parameter as :
1.strDate : which is represent datetime string.
2.fromFormat : which is represent datetime format of your given datetime string.
3.toFormat : which is represent datetime format which you wan to convert your given datetime string.
public String convertDateStringFormat(String strDate, String fromFormat, String toFormat){
try{
SimpleDateFormat sdf = new SimpleDateFormat(fromFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.trim());
return dateFormat2.format(sdf.parse(strDate));
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);
long timestamp = cursor.getLong(columnIndex);
Log.d("Server time: ", timestamp);
String localTime = sdf.format(new Date(timestamp * 1000));
Log.d("Time: ", localTime);

Format date to local setting but only for month and day

My date is in a string in the format "2013-12-31". I want to convert this to a local date based upon the user's device setting but only show the month and day. So if the user's device is set to German, the date should be converted to "31.12". In Germany, the day comes first followed by the month. I don't want the year to be included.
For Build.VERSION.SDK_INT < 18 I could not find a way to obtain a month/day format that obeys user preferences. This answer works if you are willing to accept month/day in user's locale default pattern (not their preferred order or format). My implementation uses the full numeric format in versions less than 18 or if any issues are encountered in the following carefully programmed series of steps.
Get user's numeric date format pattern as String
Reduce pattern to skeleton format without symbols or years
Obtain localized month/day format with DateFormat.getBestDateTimePattern
Reorder localized month/day format according to user preferred order. (key assumption: days and months can be naively swapped for all localized numeric formats)
This should result in a month/day pattern that obeys user's preference in localized formatting.
Get user date pattern string per this answer:
java.text.DateFormat shortDateFormat = DateFormat.getDateFormat(context);
if (shortDateFormat instanceof SimpleDateFormat) {
String textPattern = ((SimpleDateFormat) shortDateFormat).toPattern();
}
Reduce pattern to day/month skeleton by removing all characters not 'd' or 'M', example result:
String skeletonPattern = 'ddMM'
Get localized month/day format:
String workingFormat = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeletonPattern);
(note: this method requires api 18 and above and does not return values in user-preferred order or format, hence this long-winded answer):
Get user preferred date order ('M', 'd', 'y') from this method:
char[] order = DateFormat.getDateFormatOrder(context);
(note: I suppose you could parse the original pattern to get this information too)
If workingFormat is in the correct order, your job is finished. Otherwise, switch the 'd's and the 'M's in the pattern.
The key assumption here is that days and months can be naively swapped for all localized numeric formats.
DateFormat monthDayFormat = new SimpleDateFormat(workingFormat);
I think, this is the simplest solution for apps targeting API > 17:
dateFormat = SimpleDateFormat(DateFormat.getBestDateTimePattern(Locale.getDefault(), "MMMM dd"), Locale.getDefault())
A bit late, bit I also faced the same issue. That is how I solved it:
String dayMonthDateString = getDayMonthDateString("2010-12-31", "yyyy-MM-dd", Locale.GERMANY);
Log.i("customDate", "dayMonthDateString = " + dayMonthDateString);
private String getDayMonthDateString(String dateString, String dateFormatString, Locale locale)
{
try
{
boolean dayBeforeMonth = defineDayMonthOrder(locale);
String calendarDate = dateString;
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
Date date = dateFormat.parse(calendarDate);
SimpleDateFormat newDateFormat;
if (dayBeforeMonth)
{
newDateFormat = new SimpleDateFormat("dd.MM", locale);
}
else
{
newDateFormat = new SimpleDateFormat("MM.dd", locale);
}
return newDateFormat.format(date);
}
catch (ParseException e)
{
e.printStackTrace();
}
return null;
}
private boolean defineDayMonthOrder(Locale locale) throws ParseException
{
String day = "10";
String month = "11";
String year = "12";
String calendarDate = day + "." + month + "." + year;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy");
Date date = format.parse(calendarDate);
String localizedDate = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale).format(date);
int indexOfDay = localizedDate.indexOf(day);
int indexOfMonth = localizedDate.indexOf(month);
return indexOfDay < indexOfMonth ? true : false;
}
Let me know of any questions you could have related to the solution.
Keep it simple, we already have a method for this (API 18+):
String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "yyyy-MM-dd");
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
String output = format.format(currentTimeMs);
Today its 2019 July 18:
In Europe, the output will be
18.07.2019
In the US, the output will be:
07/18/2019
This works:
String dtStart = "2010-12-31";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dtStart);
SimpleDateFormat df = (SimpleDateFormat)
DateFormat.getDateInstance(DateFormat.SHORT);
String pattern = df.toLocalizedPattern().replaceAll(".?[Yy].?", "");
System.out.println(pattern);
SimpleDateFormat mdf = new SimpleDateFormat(pattern);
String localDate = mdf.format(date);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM");
try {
Date date = inputFormat.parse("2013-12-31");
String out = outputFormat.format(date);
// out is 31.12
} catch (ParseException e) {
e.printStackTrace();
}

how to get particular data from jsonarray?

I want to get the CreateDate value from xml file
the xml file is like this way.
<d:CreateDate m:type="Edm.DateTime">2012-03-18T15:11:30.403</d:CreateDate>
I created JSONObject as
JSONObject json=new WCFServices().getWhatsNew();//i get the json object WCFServices class.
JSONArray whatsnew= json.getJSONArray("d");
String CreateDate= c.getString("CreateDate");
if i try to print the value it gives me output as:
/Date(1330041600000)/
I want to get the value as like 2012-03-18T15:11:30.403
how to get it ?
I think your output is in epoch date format. So you need to convert it to normal date time. Try this for it..
public String normal_date_time(String epoch_date)
{
try
{
long epoch = Long.parseLong( epoch_date );
String dateFormat = "dd/MM/yyyy HH:mm:ss.SSS";
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epoch);
String formated_date = formatter.format(calendar.getTime());
Log.d("Date", formated_date);
return formated_date;
}
catch (Exception e)
{
// TODO: handle exception
return null;
}
You can find more about DateFormat by following links, It will help you to retrieve output in different formats.
http://developer.android.com/reference/java/text/SimpleDateFormat.html
http://developer.android.com/reference/android/text/format/DateFormat.html
Hope this will help you..And don't forget to accept this if it help you.
Thanks...

Date format : Android Contacts Birthday Anniversary

Working on Contact birthday and Anniversary:
I get details and birthday like this 12.2.2012 or 12/2/2012 or 12-02-2012 or 2/12/12
Question:
Is the date Format same across all Samsung Phones. IF yes what is the date format.
(Guess won't work on all Android phones as birthday dates are stored in many different format)
How to identify the date format like if the date is 12.2.2012 or Feb 12 2012 or any other date string pattern. Is it of format "yyyy-MM-dd" or "MMM dd, yyyy" or any other?
ex: if date is "Feb 12 2012" then date format is "MMM dd yyyy"
Unfortunately it seems different apps/vendors use different formats. My solution for this is to try parsing different formats until i either find the right one or give up.
Here is some sample code:
public static final SimpleDateFormat[] birthdayFormats = {
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyyMMdd"),
new SimpleDateFormat("yyyy.MM.dd"),
new SimpleDateFormat("yy-MM-dd"),,
new SimpleDateFormat("yyMMdd"),
new SimpleDateFormat("yy.MM.dd")
new SimpleDateFormat("yy/MM/dd"),
new SimpleDateFormat("MM-dd"),
new SimpleDateFormat("MMdd"),
new SimpleDateFormat("MM/dd"),
new SimpleDateFormat("MM.dd"),
};
.....
Date birthday = null;
for (SimpleDateFormat f : birthdayFormats) {
try {
birthday = f.parse(birthdaystr);
if (birthday!=null) {
contact.setBirthday(birthday);
break;
}
} catch (Exception e) {
continue;
}
}
Use DateFormat.getDateInstance(int style, Locale locale) instead of creating your own patterns with SimpleDateFormat.
Another way that u want to get date in String and after pass in below code
String dateStr = "04/05/2010";
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = curFormater.parse(dateStr);
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy");
String newDateStr = postFormater.format(dateObj);
The date is stored as "YYYY-MM-DD".
Use the date formater class to convert it into any format you need.
When you want to update put it in the same format as you have read.

Categories

Resources