Home » Android » Simpledateformat ignoring setTimeZone call [duplicate]

Simpledateformat ignoring setTimeZone call [duplicate]

Posted by: admin November 1, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

I think, the better way is use Joda Time instead. It’s has a ZZ attribute in format, which gives you what you want.
Usage is easy:

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZZ").withLocale(Locale.RU);

Questions:
Answers:

To get the TimeZone in UTC Format

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);

        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

        return simpleDateFormat.format(new Date());

the above format gives results as 22-10-2017 18:05:50 UTC.

To get the TimeZone in Local Format (TimeZone of Phone or device)

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);

            simpleDateFormat.setTimeZone(TimeZone.getDefault());

            return simpleDateFormat.format(new Date());

or

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);
            return simpleDateFormat.format(new Date());

the above format gives results as 22-10-2017 18:05:50 UTC+5:30.(Hint:-For India)

or

the above format gives results as 22-10-2017 18:05:50 IST.(Hint:-For India)

Hint : – if u pass this formatted String to Date like below

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);

        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

        Date d = null;

        try {
            d =simpleDateFormat.parse("22-10-2017 18:05:50 UTC");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d.toString();

the returned output will be same as device timezone i.e local Timezone or default timezone . (22-10-2017 18:05:50 UTC+5:30 or 22-10-2017 18:05:50 IST).

even though the above timezone set is UTC you will get output in Device Timezone Only , if You pass your Content Into Your Date Object.