首页 > 其他分享 >DateTime vs DateTimeOffset

DateTime vs DateTimeOffset

时间:2023-03-16 10:36:13浏览次数:43  
标签:DateTimeOffset zone offset DateTime moment vs time

DateTime vs DateTimeOffset

What is the difference between a DateTime and a DateTimeOffset and when should one be used?


Currently, we have a standard way of dealing with .NET DateTimes in a TimeZone-aware way: Whenever we produce a DateTime we do it in UTC (e.g. using DateTime.UtcNow), and whenever we display one, we convert back from UTC to the user's local time.

That works fine, but I've been reading about DateTimeOffset and how it captures the local and UTC time in the object itself.

 

回答1

From Microsoft:

These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, DateTimeOffset should be considered the default date and time type for application development.

source: "Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo", MSDN

We use DateTimeOffset for nearly everything as our application deals with particular points in time (e.g. when a record was created/updated). As a side note, we use DATETIMEOFFSET in SQL Server 2008 as well.

I see DateTime as being useful when you want to deal with dates only, times only, or deal with either in a generic sense. For example, if you have an alarm that you want to go off every day at 7 am, you could store that in a DateTime utilizing a DateTimeKind of Unspecified because you want it to go off at 7am regardless of DST. But if you want to represent the history of alarm occurrences, you would use DateTimeOffset.

Use caution when using a mix of DateTimeOffset and DateTime especially when assigning and comparing between the types. Also, only compare DateTime instances that are the same DateTimeKind because DateTime ignores timezone offset when comparing.

 

回答2

TLDR if you don't want to read all these great answers :-)

Explicit:

Using DateTimeOffset because the timezone is forced to UTC+0.

Implicit:

Using DateTime where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.


(Side note for devs: explicit is always better than implicit!)

(Side side note for Java devs, C# DateTimeOffset == Java OffsetDateTime, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)

 

Compare types related to date and time | Microsoft Learn

The DateTimeOffset structure

The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time.

The DateTimeOffset type includes all of the functionality of the DateTime type along with time zone awareness. This makes it suitable for applications that:

  • Uniquely and unambiguously identify a single point in time. The DateTimeOffset type can be used to unambiguously define the meaning of "now", to log transaction times, to log the times of system or application events, and to record file creation and modification times.

  • Perform general date and time arithmetic.

  • Preserve multiple related times, as long as those times are stored as two separate values or as two members of a structure.

 Note

These uses for DateTimeOffset values are much more common than those for DateTime values.

As a result, consider DateTimeOffset as the default date and time type for application development.

Yes, it's true that DateTimeOffset is often preferred over DateTime as the default date and time type for application development, especially in scenarios where you need to store or manipulate date and time values that are associated with a specific time zone or offset. This is because DateTimeOffset represents an unambiguous point in time with respect to a specific offset from Coordinated Universal Time (UTC), whereas DateTime does not include any information about time zone or offset, and is therefore more ambiguous and prone to errors when working with time zone conversions and daylight saving time transitions.

Furthermore, many modern APIs and frameworks, including the .NET framework, have been updated to use DateTimeOffset by default, which makes it easier to work with date and time values across different time zones and daylight saving time transitions. However, there may be some scenarios where DateTime is still a better choice, such as when you need to work with legacy systems or databases that do not support DateTimeOffset, or when you need to perform high-performance operations on large datasets that do not require time zone information.

 

What's the default datetime type of js? datetime or datetimeoffset

JavaScript does not have a built-in DateTime or DateTimeOffset type. Instead, it has a built-in Date object, which represents a point in time. The Date object stores the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC, which is also known as the Unix epoch.

The Date object does not have built-in support for time zones, so it is up to the developer to handle time zone conversions as needed. However, JavaScript does provide the Intl.DateTimeFormat object, which can be used to format dates in different time zones and locales. Additionally, there are many third-party libraries available for handling dates and time zones in JavaScript, such as Moment.js and Luxon.

 

How does moment.js handle datetimeoffset?

Moment.js is a popular JavaScript library for working with dates and times. By default, Moment.js handles dates and times in the local time zone of the user's browser.

However, Moment.js also provides a plugin called moment-timezone, which extends Moment.js to support time zones. With moment-timezone, you can create a moment object with a specific time zone offset, like so:

const moment = require('moment-timezone');

// create a moment object with a specific offset
const m = moment.utc('2022-01-05T12:34:56.789-05:00');
In this example, we're creating a moment object with a UTC time of 2022-01-05T12:34:56.789 and a time zone offset of -05:00 (Eastern Standard Time). We're using the utc function to indicate that the input time should be interpreted as UTC, and then we're using the moment-timezone plugin to apply the time zone offset.

Once you have a moment object with a specific time zone offset, you can format it for display in various ways, such as:

// format the moment object as a string in a specific time zone
const s = m.tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
console.log(s); // prints "2022-01-06 01:34:56"

In this example, we're formatting the moment object as a string in the Asia/Shanghai time zone using the tz function. We're then using the format function to specify the format of the output string. The resulting string represents the same moment in time, but with a different time zone offset.

 

Please give me some sample, which other languages use DateTimeOffset  by default?

Some programming languages and frameworks that use DateTimeOffset or similar types as the default for handling date and time values include:

  • Java: The java.time package introduced in Java 8 includes the ZonedDateTime class, which stores date and time values along with a time zone offset or zone ID.
  • Ruby: The DateTime class in Ruby includes support for time zone offsets and is often used alongside the ActiveSupport::TimeWithZone class, which provides additional features for working with time zones.
  • Python: The pytz library is commonly used in Python applications for working with time zones and daylight saving time transitions, and the datetime class in the standard library includes support for time zone offsets.

These are just a few examples, and there are many other languages and frameworks that support working with DateTimeOffset or similar types.

 

 

 

 

标签:DateTimeOffset,zone,offset,DateTime,moment,vs,time
From: https://www.cnblogs.com/chucklu/p/17221343.html

相关文章

  • Vscode golang初始化配置
    1、下载安装GO插件2、写代码时vscode提示你需要安装go插件,点击installall进行安装如果安装失败,原因是有道墙,解决方法是,配置国内源如下:goenv-wGO111MODULE=ongoe......
  • 39 openEuler搭建FTP服务器-安装管理vsftpd服务
    39openEuler搭建FTP服务器-安装管理vsftpd服务39.1安装vsftpd使用vsftpd需要安装vsftpd软件,在已经配置yum源的情况下,通过root权限执行如下命令,即可完成vsftpd的安装。#......
  • tvs管如何确定方向?单向双向有什么差异?
    tvs管A和CA是什么意思?有什么区别呢?tvs管有方向吗?tvs管如何确定方向?tvs管单双向有什么差异?双向tvs管型号,常用的有哪些?tvs管上有根阴极线,是什么意思?tvs管如何焊接,需要区分正负......
  • ubuntu上VScode的安装与配置
    1.进入vscode官网:https://code.visualstudio.com/2.右上角点击download,选择ubuntu的.deb安装包进行下载 3.进入下载好的.deb安装包目录下,在该目录下打开终端,输入sudo......
  • VS CODE运行DJango项目中遇到:{无法加载文件 D:\code\python_project\virtualenv\e
    如题在vscode中在切换python解释器(输入之前创建的虚拟环境的解释器路径)后,打开控制板会报一下错误:无法加载文件D:\code\python_project\virtualenv\env-py3.8.2\Scripts......
  • VS Code 远程连接 2008R2【2008R2安装SSH服务,支持远程命令行ssh登录2008R2】
    参考https://www.jianshu.com/p/b5b760bc56ff(主要参考)https://zhuanlan.zhihu.com/p/122999157https://github.com/PowerShell/Win32-OpenSSH/releases(Win-OpenSSH仓......
  • vscode问题
    解决VSCode无缘无故卡顿的问题:https://blog.csdn.net/u011296285/article/details/121121118 ......
  • vscode 中运行 c# 代码?
    目前来看,只能运行,调试要用其它插件且需要配置,太复杂,不如用linqpad。使用插件CodeRunner,前提是先要安装scriptcs,这个还牵扯新旧版本的问题,最新版本名字改成了 dotnet-s......
  • vsftpd的一点SELinux设置
    在开了SELinux和防火墙的情况下,使用chroot_local_user=YES锁定用户在自己的home目录中,没想到vsftp的问题。FTP登录报错:500OOPS:cannotchangedirectory。下面来看看产......
  • 使用vscode + vite + vue3+ vant 搭建vue3脚手架
    【术栈】开发工具:VSCode代码管理:Git前端框架:Vue3构建工具:Vite路由:vue-router4x状态管理:vuex4xAJAX:axiosUI库:vant数据模拟:mockjscss预处理:sass构建vue3项目1,安装 vite......