How to Get the Timezone Offset in Gmt(Like Gmt+7:00) from Android Device

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

This code return me GMT offset.

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);

It returns the time zone offset like this: +0530

If we use SimpleDateFormat below

DateFormat date = new SimpleDateFormat("z",Locale.getDefault());
String localTime = date.format(currentLocalTime);

It returns the time zone offset like this: GMT+05:30

Get timezone in GMT from Android devices

Using GregorianCalender you can get the timezone please check below
code

 Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
int mGMTOffset = mTimeZone.getRawOffset();

double sZone = (double) (TimeUnit.MINUTES.convert(mGMTOffset,TimeUnit.MILLISECONDS));
string timeDiff = sZone / 60;

How to Get device timezone?

The desired format appears to be in ISO 8601 format, in which case you can use ISO8601DateFormatter:

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withTimeZone, .withColonSeparatorInTimeZone]
dateFormatter.timeZone = TimeZone.current
let formattedTimezone = dateFormatter.string(from: Date())

Note that I have used Date() in the last line. This will output the offset from GMT of the timezone at the current instant. Replace this with a Date of your choice to get the offset from GMT of that timezone at that Date instead.

Convert Date/Time for given Timezone - java

For me, the simplest way to do that is:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));


Related Topics



Leave a reply



Submit