获取表示 UTC 偏移量的格式化字符串的最佳方法是什么?

发布于 2024-10-15 06:21:59 字数 457 浏览 4 评论 0原文

我需要像这样格式化日期:20110202192008-0500。下面的代码可以解决这个问题,但我想知道在 c# 3.5 中是否有更好/更干净的方法来做到这一点。谢谢!!

  var date = DateTime.Now;
  var strDate = TimeZoneInfo.ConvertTimeToUtc(date).ToString("yyyyMMddHHmmss");
  var offsetHours = TimeZoneInfo.Local.GetUtcOffset(date).Hours.ToString("00");
  var offsetMinutes = TimeZoneInfo.Local.GetUtcOffset(date).Minutes.ToString("00");
  Console.Write(string.Concat(strDate, offsetHours, offsetMinutes));

I need to format a date like so: 20110202192008-0500. The following code does the trick but I was wondering if there is a better/cleaner way to do this in c# 3.5. Thanks!!

  var date = DateTime.Now;
  var strDate = TimeZoneInfo.ConvertTimeToUtc(date).ToString("yyyyMMddHHmmss");
  var offsetHours = TimeZoneInfo.Local.GetUtcOffset(date).Hours.ToString("00");
  var offsetMinutes = TimeZoneInfo.Local.GetUtcOffset(date).Minutes.ToString("00");
  Console.Write(string.Concat(strDate, offsetHours, offsetMinutes));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

知足的幸福 2024-10-22 06:21:59

怎么样:

.NET 4

 var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 Console.WriteLine(DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));

.NET 3.5

 var utcAlmostFormat = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 var utcFormat = System.Text.RegularExpressions.Regex.Replace(utcAlmostFormat, @"(\d\d):(\d\d):(\d\d)",@"$1$2");
 Console.WriteLine(utcFormat);

Go Steelers(来自拉斯维加斯大道上的一个人)

How about this:

.NET 4

 var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 Console.WriteLine(DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));

.NET 3.5

 var utcAlmostFormat = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 var utcFormat = System.Text.RegularExpressions.Regex.Replace(utcAlmostFormat, @"(\d\d):(\d\d):(\d\d)",@"$1$2");
 Console.WriteLine(utcFormat);

Go Steelers (from a guy in the Strip)

还给你自由 2024-10-22 06:21:59

如果您有 DateTimeOffset,自定义说明符 zzz 将输出时区偏移量,尽管采用更标准的“+HH:mm”格式。如果您不需要冒号,则可以使用字符串替换来解决问题。

Debug.WriteLine(DateTimeOffset.Now.ToString("yyyyMMddHHmmsszzz").Replace(":", ""));
// Result: "20110202153631-0500"

If you have a DateTimeOffset, the custom specifier zzz will output the timezone offset, though in the more standard "+HH:mm" format. If you don't want the colon, a string replace will do the trick.

Debug.WriteLine(DateTimeOffset.Now.ToString("yyyyMMddHHmmsszzz").Replace(":", ""));
// Result: "20110202153631-0500"
挥剑断情 2024-10-22 06:21:59

以下是一些适用于 .Net 3.5 和 .Net 4.0 的扩展方法,它们将以非常直接的方式完全满足您的要求:

public static string ToStringWithOffset(this DateTime dt)
{
  return new DateTimeOffset(dt).ToStringWithOffset();
}

public static string ToStringWithOffset(this DateTime dt, TimeSpan offset)
{
  return new DateTimeOffset(dt, offset).ToStringWithOffset();
}

public static string ToStringWithOffset(this DateTimeOffset dt)
{
  string sign = dt.Offset < TimeSpan.Zero ? "-" : "+";
  int hours = Math.Abs(dt.Offset.Hours);
  int minutes = Math.Abs(dt.Offset.Minutes);

  return string.Format("{0:yyyyMMddHHmmss}{1}{2:00}{3:00}", dt, sign, hours, minutes);
}

您现在可以在任何您希望的 DateTime 或 DateTimeOffset 上调用这些方法。例如:

string s = DateTime.Now.ToStringWithOffset();

string s = DateTimeTimeOffset.Now.ToStringWithOffset();

TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(someDate);
string s = someArbitraryTime.ToStringWithOffset(offset);

或您能想到的任何其他方式。

Here are some extension methods that will work in both .Net 3.5 and .Net 4.0 that will do exactly what you are asking in a very straight-forward way:

public static string ToStringWithOffset(this DateTime dt)
{
  return new DateTimeOffset(dt).ToStringWithOffset();
}

public static string ToStringWithOffset(this DateTime dt, TimeSpan offset)
{
  return new DateTimeOffset(dt, offset).ToStringWithOffset();
}

public static string ToStringWithOffset(this DateTimeOffset dt)
{
  string sign = dt.Offset < TimeSpan.Zero ? "-" : "+";
  int hours = Math.Abs(dt.Offset.Hours);
  int minutes = Math.Abs(dt.Offset.Minutes);

  return string.Format("{0:yyyyMMddHHmmss}{1}{2:00}{3:00}", dt, sign, hours, minutes);
}

You can now call these on any DateTime or DateTimeOffset you wish. For example:

string s = DateTime.Now.ToStringWithOffset();

or

string s = DateTimeTimeOffset.Now.ToStringWithOffset();

or

TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(someDate);
string s = someArbitraryTime.ToStringWithOffset(offset);

or any other number of ways you can think of.

寂寞笑我太脆弱 2024-10-22 06:21:59

我们发现 DateTimeOffset.ToString("o") 最适合此目的。示例:

DateTime.UtcNow.UtcToDateTimeOffset(User.GetTimeZone()).ToString("o");

如果您需要从 DateTime 进行转换,请使用辅助方法,例如:

    /// <summary>Converts from a UTC DateTime to the user's local DateTime</summary>
    /// <param name="utcDateTime">UTC DateTime</param>
    /// <param name="timeZoneInfo">The time zone info.</param>
    /// <returns>The DateTime in the user's time zone</returns>
    public static DateTimeOffset UtcToDateTimeOffset(this DateTime utcDateTime, TimeZoneInfo timeZoneInfo = null)
    {
        if (utcDateTime.Kind != DateTimeKind.Utc)
        {
            throw new InvalidTimeZoneException("Converting UTC to Local TimeZone, but was not UTC.");
        }

        DateTimeOffset dto = new DateTimeOffset(utcDateTime, TimeSpan.Zero);

        return timeZoneInfo.IsNotNull() ? dto.ToOffset(timeZoneInfo.GetUtcOffset(dto)) : dto;
    }

We found that DateTimeOffset.ToString("o") is best for that. Example:

DateTime.UtcNow.UtcToDateTimeOffset(User.GetTimeZone()).ToString("o");

If you need to convert from DateTime, use helper method like:

    /// <summary>Converts from a UTC DateTime to the user's local DateTime</summary>
    /// <param name="utcDateTime">UTC DateTime</param>
    /// <param name="timeZoneInfo">The time zone info.</param>
    /// <returns>The DateTime in the user's time zone</returns>
    public static DateTimeOffset UtcToDateTimeOffset(this DateTime utcDateTime, TimeZoneInfo timeZoneInfo = null)
    {
        if (utcDateTime.Kind != DateTimeKind.Utc)
        {
            throw new InvalidTimeZoneException("Converting UTC to Local TimeZone, but was not UTC.");
        }

        DateTimeOffset dto = new DateTimeOffset(utcDateTime, TimeSpan.Zero);

        return timeZoneInfo.IsNotNull() ? dto.ToOffset(timeZoneInfo.GetUtcOffset(dto)) : dto;
    }
审判长 2024-10-22 06:21:59

您可以使用 DateTime 之一 标准格式 或创建 自定义格式

// Round-trip date/time pattern: "O", "o"
DateTime.Now.ToString("o") // "2018-01-15T11:00:50.5604578-05:00"
DateTime.UtcNow.ToString("o") // "2018-01-15T16:00:50.5604578Z"

// Universal sortable date/time pattern: "u"
DateTime.Now.ToString("u") // "2018-01-15 16:00:50.5604578Z"
DateTime.UtcNow.ToString("u") // "2018-01-15 16:00:50.5604578Z"

// Custom format
DateTime.Now.ToString("yyyyMMddHHmmssK") // "20180115160050-05:00"
DateTime.UtcNow.ToString("yyyyMMddHHmmssK") // "20180115160050Z"

You can use one of the DateTime Standard Formats or create a Custom Format.

// Round-trip date/time pattern: "O", "o"
DateTime.Now.ToString("o") // "2018-01-15T11:00:50.5604578-05:00"
DateTime.UtcNow.ToString("o") // "2018-01-15T16:00:50.5604578Z"

// Universal sortable date/time pattern: "u"
DateTime.Now.ToString("u") // "2018-01-15 16:00:50.5604578Z"
DateTime.UtcNow.ToString("u") // "2018-01-15 16:00:50.5604578Z"

// Custom format
DateTime.Now.ToString("yyyyMMddHHmmssK") // "20180115160050-05:00"
DateTime.UtcNow.ToString("yyyyMMddHHmmssK") // "20180115160050Z"
葬心 2024-10-22 06:21:59

尝试使用

var date = DateTimeOffset.Now;
var timestamp = $"{date:yyyy-MM-dd'T'HH:mm:ss.fff}{date.Offset.Ticks:+;-;}{date.Offset:hhmm}";

...或类似的东西。

Try to use

var date = DateTimeOffset.Now;
var timestamp = 
quot;{date:yyyy-MM-dd'T'HH:mm:ss.fff}{date.Offset.Ticks:+;-;}{date.Offset:hhmm}";

... or something like this.

二手情话 2024-10-22 06:21:59

我觉得方法有很多,比如:

  var offset = TimeZoneInfo.Local.BaseUtcOffset;
  string result = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + offset.Hours.ToString("00") + offset.Minutes.ToString("00");

I think there are a lot of ways, for example:

  var offset = TimeZoneInfo.Local.BaseUtcOffset;
  string result = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + offset.Hours.ToString("00") + offset.Minutes.ToString("00");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文