0

I have the following code:

SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(date);

When I call this code with a date object, then it returns the same date (as String obviously) without setting the timezone.

As I understood a java.util.Date object is timezone independent. So if I set the timezone on the SimpleDateFormat then it should change. But it doesn't.

If I check sdf.getTimeZone() then I see that my timezone is set correctly to UTC+03:00.

Does someone know how to solve this problem?

  • You're right, `java.util.Date` is not timezone aware. When you create a `new SimpleDateFormat`, it uses the JVM's default timezone, so setting `Timezone.getDefault()` as you did is redundant (that's why you get the same result, setting it or not). When formatting, there'll always be some timezone behind the scenes. –  Oct 22 '17 at 12:02

2 Answers2

0

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.

Santhosh
  • 51
  • 7
-1

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);
Scrobot
  • 1,911
  • 3
  • 19
  • 36