Convert UTC DateTime to another Time Zone
Have a look at the DateTimeOffset structure:
// user-specified time zone
TimeZoneInfo southPole =
TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time");
// an UTC DateTime
DateTime utcTime = new DateTime(2007, 07, 12, 06, 32, 00, DateTimeKind.Utc);
// DateTime with offset
DateTimeOffset dateAndOffset =
new DateTimeOffset(utcTime, southPole.GetUtcOffset(utcTime));
Console.WriteLine(dateAndOffset);
For DST see the TimeZoneInfo.IsDaylightSavingTime method.
bool isDst = southpole.IsDaylightSavingTime(DateTime.UtcNow);
Converting UTC dates to other timezones
It turns out the code was almost correct, what I didn't take into account was that when parsing the String
to get a Date
object initially, it uses default system TimeZone
, so the source date was not in UTC as I expected.
The trick was to set the timezone when parsing the date to UTC and then set it to destination TimeZone
. Something like this:
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = sourceFormat.parse("2011-03-01 15:10:37"); // => Date is in UTC now
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
Convert UTC date to current timezone
it print GMT+02 because this is your "local" timezone.
if you want to print the date without timezone information, use SimpleDateFormat to format the date to you liking.
edit : adding the code example (with your variable 'myDate')
SimpleDateFormat inputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = inputSDF.parse("2016-09-25 17:26:12");
//
SimpleDateFormat outputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputSDF.format(myDate));
System.out.println(TimeZone.getDefault().getID());
yield on the (my) console (with my local timezone).
2016-09-25 19:26:12
Europe/Paris
convert date and time in any timezone to UTC zone
You cannot "convert that date values" to other timezones or UTC. The type java.util.Date
does not have any internal timezone state and only refers to UTC by spec in a way which cannot be changed by user (just counting the milliseconds since UNIX epoch in UTC timezone leaving aside leapseconds).
But you can convert the formatted String-representation of a java.util.Date
to another timezone. I prefer to use two different formatters, one per timezone (and pattern). I also prefer to use "Asia/Kolkata" in your case because then it will universally works (IST could also be "Israel Standard Time" which will be interpreted differently in Israel):
DateFormat formatterIST = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // better than using IST
Date date = formatterIST.parse("15-05-2014 00:00:00");
System.out.println(formatterIST.format(date)); // output: 15-05-2014 00:00:00
DateFormat formatterUTC = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
System.out.println(formatterUTC.format(date)); // output: 14-05-2014 18:30:00
// output in system timezone using pattern "EEE MMM dd HH:mm:ss zzz yyyy"
System.out.println(date.toString()); // output in my timezone: Wed May 14 20:30:00 CEST 2014
Trying to convert UTC time with specific time zones
You can create a date for the sunrise by adding the timezone
value.
The example below will produce a date and time in the timezone of the weather record (Horinouchi), NOT the timezone of the user.
const data = {
"dt": 1609176171,
"sys": {
"type": 1,
"id": 8074,
"country": "JP",
"sunrise": 1609192224,
"sunset": 1609227369
},
"timezone": 32400,
"id": 1862143,
"name": "Horinouchi",
"cod": 200
};
// extract sunrise and timezone offset in UNIX epoch seconds
const {
sys: {sunrise},
timezone
} = data;
// create Date object for sunrise with timezone offset
const srTime = new Date((sunrise+timezone)*1000);
// convert number to a 2-digit string
const twoDigits = (val) => {
return ('0' + val).slice(-2);
};
const year = srTime.getUTCFullYear();
const month = twoDigits(srTime.getUTCMonth()+1);
const dayOfMonth = twoDigits(srTime.getUTCDate());
const hours = twoDigits(srTime.getUTCHours());
const minutes = twoDigits(srTime.getUTCMinutes());
const seconds = twoDigits(srTime.getUTCSeconds());
console.log(`${year}-${month}-${dayOfMonth} ${hours}:${minutes}:${seconds}`);
How to convert UTC datetime to another timezone?
Use DateTime
and DateTimeZone
.
$date = new DateTime('2012-07-16 01:00:00 +00');
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04
echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00
Convert date to another timezone in JavaScript
Here is the one-liner:
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)
// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17
// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.
Convert UTC date time to local date time
Append 'UTC' to the string before converting it to a date in javascript:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
Related Topics
Android Wifi How to Detect When Specific Wifi Connection Is Available
How to Send the Sms More Than 160 Character
Android - Add Textview to Layout When Button Is Pressed
Signal 11 Sigsegv Crash Android
Checking a Checkbox in Listview Makes Other Random Checkboxes Checked Too
How to Create Parallelogram Shape Background
Broadcastreceiver as Inner Class
Android; Geocoder, Why Do I Get "The Service Is Not Available"
Why Getapplicationcontext() in Constructor of Activity Throws Null Pointer Exception
Android Device Does Not Show Up in Adb List
How to Change the Tabs Images in the Tabhost
Gridview with Different Cells Sizes, Pinterest Style
Find Out the Running Process Id by Package Name
Register to Be Default App for Custom File Type
Fragment-Fragment Communication in Android