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.
Related
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
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();
}
There seems to be many ways to format date and time in Android - but none exactly the way I want ;-)
The methods I have been able to find involve the Locale (directly or indirectly) - but the correct way must be to use what the user has configured in "Settings - Date and time".
Using for example:
String res = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT, java.text.DateFormat.MEDIUM).format(date);
Log.d("", res);
logs: 4/9/13 12:11:34 PM
and
res = android.text.format.DateUtils.formatDateTime(getActivity(), date.getTime(), android.text.format.DateUtils.FORMAT_SHOW_TIME | android.text.format.DateUtils.FORMAT_SHOW_DATE | android.text.format.DateUtils.FORMAT_SHOW_YEAR);
Log.d("", res);
logs: 12:11 April 9, 2013
BUT this is not how it is configured and when I look at a file's date and time it is written as: 09/04/2013 12:11
So how do I get the formatting strings (like "yyyy-MM-dd" and "HH:mm") configured in "Settings - Date and time" or alternatively, how do I get a Date formatted according to these rules?
Try to use below code:
public static String convertDateToUserFormat(final Date inputDate) {
if (inputDate != null) {
return getDateFormat().format(inputDate);
}
return null;
}
private static DateFormat getDateFormat() {
final String format = Settings.System.getString(context.getContentResolver(),
Settings.System.DATE_FORMAT);
if (TextUtils.isEmpty(format)) {
return android.text.format.DateFormat
.getDateFormat(context);
}
return new SimpleDateFormat(format);
}
Format dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
formattedDate = formatter.parse(yourDateString);
For more info on DateFormatter check out the developer doc
here is the example for date format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
u can follow this link for more info enter link description here
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)/";
}
I store current time in database each time application starts by user.
Calendar c = Calendar.getInstance();
String str = c.getTime().toString();
Log.i("Current time", str);
In database side, I store current time as string (as you see in above code). Therefore, when I load it from database, I need to cast it to Date object. I saw some samples that all of them had used "DateFormat". But my format is exactly as same as Date format. So, I think there is no need to use "DateFormat". Am I right?
Is there anyway to directly cast this String to Date object? I want to compare this stored time with current time.
update
Thanks all. I used following code:
private boolean isPackageExpired(String date){
boolean isExpired=false;
Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");
if (new Date().after(expiredDate)) isExpired=true;
return isExpired;
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
From String to Date
String dtStart = "2010-10-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
From Date to String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println("Current Date Time : " + dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date
and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
You can use java.time in Android now, either by using Android API Desugaring or importing the ThreeTenAbp.
With java.time enabled, you can do the same operations with less code and less errors.
Let's assume you are passing a String containing a datetime formatted in ISO standard, just as the currently accepted answer does.
Then the following methods and their usage in a main may show you how to convert from and to String:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
ZonedDateTime odt = convert(dtStart);
System.out.println(odt);
}
and
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
OffsetDateTime odt = convert(dtStart);
System.out.println(odt);
}
will print the line
2010-10-15T09:27:37Z
when there are the corresponding methods
public static OffsetDateTime convert(String datetime) {
return OffsetDateTime.parse(datetime);
}
or
public static ZonedDateTime convert(String datetime) {
return ZonedDateTime.parse(datetime);
}
but of course not in the same class, that would not compile...
There's a LocalDateTime, too, but that would not be able to parse a zone or offset.
If you want to use custom formats for parsing or formatting output, you can utilize a DateTimeFormatter, maybe like this:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = ZonedDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss zz uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
which will output
Fri Oct 15 09:27:37 Z 2010
For an OffsetDateTime, you would need to adjust the pattern a little:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = OffsetDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss xxx uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
This will produce a (slightly) different output:
Fri Oct 15 09:27:37 +00:00 2010
That's because a ZonedDateTime considers named time zones with changing offsets (due to daylight saving times or anything similar) while an OffsetDateTime just knows an offset from UTC.
It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.
One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);