How to Convert a Date to Utc

How to convert a Date to UTC?

The toISOString() method returns a string in simplified extended ISO
format (ISO 8601), which is always 24 or 27 characters long
(YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ,
respectively). The timezone is always zero UTC offset, as denoted by
the suffix "Z".

Source: MDN web docs

The format you need is created with the .toISOString() method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:

This will give you the ability to do what you need:

var isoDateString = new Date().toISOString();
console.log(isoDateString);

Javascript: Convert date to UTC format

new Date('2016-06-18 05:18:27').toUTCString()

The toUTCString() method converts a date to a string, using the UTC time zone.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString

And in fact, your format maybe the result of this:

new Date('2016-06-18 05:18:27').toISOString()

And by the way, if you want to format the date, moment.js or fecha may be better.

You can also find similar answers in How do you convert a JavaScript date to UTC?

Converting new Date() to UTC format in typescript, angular

personModel: PersonDetail;    

const activationDate = new Date();

this.personModel.activationDate = new Date(activationDate.getUTCFullYear(),
activationDate.getUTCMonth(),
activationDate.getUTCDate(),
activationDate.getUTCHours(),
activationDate.getUTCMinutes(),
activationDate.getUTCSeconds()
);

OR
Can use a separate method to get UTCDate

const activationDate = this.getNowUTC();    

private getNowUTC() {
const now = new Date();
return new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
}

A good article on converting DateTime

SQL Server - Convert date field to UTC

If they're all local to you, then here's the offset:

SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime

and you should be able to update all the data using:

UPDATE SomeTable
SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)

Would that work, or am I missing another angle of this problem?

Convert today date into UTC string

Angular Docs:

formatDate

DatePipe (format string) docs

Use the timezone third parameter:

import {formatDate} from '@angular/common';
today = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss', 'en', '+0000');

console.log(formatDate(new Date(), 'yyyy-MM-ddThh:mm:ssZZZZZ', 'en', 'GMT'))

How to convert Date string into UTC Date object?

The java.util.Date class is not optimal to start with. While it looks like a full date from the outside, it actually only represents a timestamp without storing actual timezone information.

On Java 8 and later I'd suggest to stick with the better designed java.time.* classes.

    String dbTime = "01/01/1998 12:30:00";
String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";

// parsed date time without timezone information
LocalDateTime localDateTime = LocalDateTime.parse(dbTime, DateTimeFormatter.ofPattern(DATE_FORMAT));

// local date time at your system's default time zone
ZonedDateTime systemZoneDateTime = localDateTime.atZone(ZoneId.systemDefault());

// value converted to other timezone while keeping the point in time
ZonedDateTime utcDateTime = systemZoneDateTime.withZoneSameInstant(ZoneId.of("UTC"));

// timestamp of the original value represented in UTC
Instant utcTimestamp = systemZoneDateTime.toInstant();

System.out.println(utcDateTime);
System.out.println(utcTimestamp);

As you can see from the names alone there are different classes for different use-cases of dates.

java.time.LocalDateTime for example only represents a date and time without a specific timezone context and therefore can be used to parse your string value directly.

To convert timezones, you first have to convert into the a ZonedDateTime, which accepts date, time and timezone. I've intialized the sample on "systemDefault", as on most smaller apps you can use the JVM and OS'es default value to assume the current timezone.
You could also use ZoneId.of("America/Los_Angeles") directly if you want to make sure the value is interpreted as pacific time.

This value can be converted into another ZonedDateTime in another timezone, e.g. UTC.

For UTC especially you could also use the Instant class, which represents only a UTC timestamp and can also be used as a basis for most other types

How to convert a date to UTC properly and then convert it back?

You convert back to local time using ToLocalTime(). It will see that the date/time is in July, so with DST, and hence it will shift by 4 hours and not by 5.

If you have a client (e.g. Web browser) connecting to the server you will ultimately want the date/time converted to the local time of the client, not of the server. To do this the best way is to use TimeZone.ToLocalTime(): send to the served the time-zone the client is in and then convert directly to that time-zone all the time.

NEVER add/subtract hours - always go through the time zone and use TimeZoone.ToLocalTime(). Adding/subtracting hours won't work when DST is involved.

Note that it is not possible to get the current (local) time-zone from inside a browser. If your client is a browser you need to get the time-zone from some sort of configuration or have the user enter it.

Note also that once you start to handle different time zones you no longer have just dates - you always have to deal with complete date-times: if you strip or loose the time part all the conversions won't work any more.

Concerning question 2: UTC time is universal, not based on any specific time zone, hence once you convert to UTC you don't have to worry any more about the time-zone of the servers.

Convert a given date to UTC date time

It depends on your java version and as always there are many ways to solve this. With java 8 in place you can do something like this:

First you need to parse the date into a java.time.LocalDate

String date = "2017-01-01";
final LocalDate localDate = LocalDate.parse(date);
System.out.println(localDate);

Which prints

2017-01-01

From this LocalDate you can create your UTC start and end dates as types of java.time.ZonedDateTime as follows

final ZoneId utc = ZoneId.of("UTC");
final ZonedDateTime start = LocalDate.parse(date).atStartOfDay(utc);
final ZonedDateTime end = LocalDate.parse(date).atTime(23, 59, 59).atZone(utc);
System.out.println(end);

This prints

2017-01-01T00:00Z[UTC]
2017-01-01T23:59:59Z[UTC]

Notice for the end date you could also do

final ZoneId utc = ZoneId.of("UTC");
final ZonedDateTime end = LocalDate.parse(date).atTime(LocalTime.MAX).atZone(utc);

Which gives you a few more digits

2017-01-01T23:59:59.999999999Z[UTC]

See also

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html

Hope it helps!

Convert UTC datetime string to local datetime

If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)



Related Topics



Leave a reply



Submit