Applying timezone to date format not working [duplicate] - java

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 6 years ago.
In my Android app I have a string like this, String date = "2016-09-24T06:24:01Z";
I use this code to turn it into a nicer looking date format:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getDefault());
DateFormat formatted = new SimpleDateFormat(format);
Date result = dateFormat.parse(date);
dateString = formatted.format(result);
However it's not applying the timezone. I've tried setting it on both dateFormat and formatted and no matter what I do it still comes back with 6:24 AM.
Shouldn't TimeZone.getDefault() be looking at the timezone on the device running the app and adjusting the time accordingly?

As your are using java.util.date which have no Time Zone. It represent UTC/GMT no Time Zone offset. See below thing.
so change this line
dateFormat.setTimeZone(TimeZone.getDefault());
to this
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
or this
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

If you know the current time zone:
TimeZone tzone = TimeZone.getTimeZone("America/Los_Angeles");
tzone.setDefault(tzone);
If you do not know the current timezone:
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
TimeZone tzone = TimeZone.getTimeZone(name);
tzone.setDefault(tzone);

Related

Java: Get time in "hh:MM:ss a" format [duplicate]

This question already has answers here:
How to format date and time in Android?
(26 answers)
Closed 3 years ago.
I was building an android app and i was using Date class in my project to get the current date. I formatted the date with simpledateformatter and displayed it like dd-mm-yyyy (i.e. day month year) .
Now i also want to get the time in format of hh:MM:ss a (hours minutes seconds AM/PM)
As i was using date's instance i saw that it displays date and time also ( in default format). So i tried to fetch time from the date's instance.(let's say d is date class instance). I also found getTime() method of date class and performed d.getTime() but it returned me a long (which is duration from some fixed time from past to current time). Now i want time in desired format but this getTime() method is giving me long.
May you provide me some way on how to process this long value to get the desired format of time out of it. For example , d.getTime() return me some value( say 11233) and i want in format like this (11:33:22).
You can make that
private final String DATE_FORMAT = "dd.MM.yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date got = sdf.parse(date);
It returns Date with time to you
Use this snippet to get the date and time both.
public String currentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa"); //it will give you the date in the formate that is given in the image
String datetime = dateformat.format(c.getTime()); // it will give you the date
return datetime;
}
Note: Take a look in the image .
Date().getTime() is providing you the timestamp
Change the format to your requirement like mm:hh:ss a
Kotlin
fun getDateTime():String {
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
val date = Date()
return inputFormat.format(date.time)
}
JAVA
private String getDateTime(){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
return format.format(new Date().getTime());
}

How to do subtraction from a particular date using Java [duplicate]

This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);

How to convert this Date string into a long? [duplicate]

This question already has answers here:
Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]
(2 answers)
Closed 6 years ago.
I am having issues converting a String that has this format for date from the server into a long?
Example Date String - "2016-07-04T00:02:34.457Z" (Note this is a string)
I tried this below but needs try catch around gmt, when I add it and a not null around cmtDt - then I initialize cmtDt to 0 pre setting it on the bottom and it is always 0.
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
formatter.setTimeZone(tz);
Date gmt = formatter.parse(comment.getDateCommented());
cmtDt = gmt.getTime();
First, your input String includes milliseconds (and your format does not). Second, your input String includes a literal Z (which is presumably to indicate a UTC timezone). Finally, getting your system timezone and assigning it to the formatter isn't reliably going to be UTC. You need something like,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println(cmtDt);
} catch (Exception e) {
e.printStackTrace();
}
Which I ran, and got
1467590554457
Your format string for the SimpleDateFormat needs to be:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
My test code that works is:
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
formatter.setTimeZone(tz);
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println("cmtDt = " + cmtDt);
The format in SDF needs to be fixed. The following will help you.
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
formatter.setTimeZone(tz);
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println(cmtDt);
Prints : 1467599640457

java - Convert date string to UTC time [duplicate]

This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 6 years ago.
I just needed a sample code block or suggestion to convert the following date string to utc time and find difference with current time in java?
date string "2016-03-21T15:58:36-04:00"
Thanks in advance
You need to format the date string in following way:
String string = "2016-03-21T15:58:36-04:00";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
Date date = format.parse(string);
Then you just need to use Date APIs to find the time difference.
public static long getMillisFrom(String inStrDate) {
DateFormat ISO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
Date inDate = ISO_DATE_FORMAT.parse(inStrDate);
Date curDate = new Date();
long diffMillis = curDate().getTime() - inDate.getTime();
return diffMillis
}

Converting a date string from a timezone to different time zone

I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

Categories