How to convert datetime.date.today() to UTC time?
Use utcnow
:
today = datetime.datetime.utcnow().date()
Is Date.today in UTC?
TL;DR: Date.today
uses the system’s local time zone. If you require it be in UTC, instead get the date from a UTC time, e.g. Time.now.utc.to_date
.
Dates do not have timezones, since they don't represent a time.
That said, as for how it calculates the current day, let's look at this extract from the code for Date.today
:
time_t t;
struct tm tm;
// ...
if (time(&t) == -1)
rb_sys_fail("time");
if (!localtime_r(&t, &tm))
rb_sys_fail("localtime");
It then proceeds to use use tm
to create the Date
object. Since tm
contains the system's local time using localtime()
, Date.today
therefore uses the system's local time, not UTC.
You can always use Time#utc
on any Time
convert it in-place to UTC, or Time#getutc
to return a new equivalent Time
object in UTC. You could then call Time#to_date
on that to get a Date
. So: some_time.getutc.to_date
.
If you’re using ActiveSupport’s time zone support (included with Rails), note that it is completely separate from Ruby’s time constructors and does not affect them (i.e. it does not change how Time.now
or Date.today
work). See also ActiveSupport extensions to Time
.
How can I get the current date and time in UTC or GMT in Java?
java.util.Date
has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?
To be precise: the value within a java.util.Date
is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date
is the same around the world at any particular instant, regardless of local time zone.
I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString()
which also uses the local timezone, or a SimpleDateFormat
instance, which, by default, also uses local timezone.
If this isn't the problem, please post some sample code.
I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.
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);
How do I get a value of datetime.today() in Python that is timezone aware?
In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. (Edit: Python 3.9 introduces zoneinfo
in the standard library which does provide this functionality.)
On Windows, there's win32timezone.utcnow()
, but that's part of pywin32. I would rather suggest to use the pytz library, which has a constantly updated database of most timezones.
Working with local timezones can be very tricky (see "Further reading" links below), so you may rather want to use UTC throughout your application, especially for arithmetic operations like calculating the difference between two time points.
You can get the current date/time like so:
import pytz
from datetime import datetime
datetime.utcnow().replace(tzinfo=pytz.utc)
Mind that datetime.today()
and datetime.now()
return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc)
to them would not be correct.
Another nice way to do it is:
datetime.now(pytz.utc)
which is a bit shorter and does the same.
Further reading/watching why to prefer UTC in many cases:
- pytz documentation
- What Every Developer Should Know About Time – development hints for many real-life use cases
- The Problem with Time & Timezones - Computerphile – funny, eye-opening explanation about the complexity of working with timezones (video)
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'))
DateTime.Now vs. DateTime.UtcNow
DateTime.UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime.Now gives the date and time as it would appear to someone in your current locale.
I'd recommend using DateTime.Now
whenever you're displaying a date to a human being - that way they're comfortable with the value they see - it's something that they can easily compare to what they see on their watch or clock. Use DateTime.UtcNow
when you want to store dates or use them for later calculations that way (in a client-server model) your calculations don't become confused by clients in different time zones from your server or from each other.
Javascript Date Now (UTC) in yyyy-mm-dd HH:mm:ss format
We should use in-built toISOString
function to covert it to ISO date format and remove not required data using string manipulation.
let datenow = new Date();
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
return date.toISOString().replace("T"," ").substring(0, 19);
}
Related Topics
Getting Only New Mail from an Imap Server
What's the Difference Between Process.Fork and Process.Spawn in Ruby 1.9.2
How to See the Dependency Tree Just from Gemfile
Is There a "Main" Method in Ruby Like in C
In-Place Progress Output in the Terminal or Console
Error While Installing Ruby Using Rvm
How to Write Columns Header to a CSV File with Ruby
In Ruby, How to Check If Method "Foo=()" Is Defined
Activerecord Select Except Columns
Ruby - Keyword Arguments - Can You Treat All of the Keyword Arguments as a Hash? How
Accessing Objects Memory Address in Ruby
How to Break from Nested Loops in Ruby
How to Convert from a String to Object Attribute Name
Install Ruby Curb Gem in Windows Xp
How Would I Save Multiple Records at Once in Rails
Homebrew Install: Failed During: Git Fetch Origin Master:Refs/Remotes/Origin/Master -N --Depth=1