我们公司的产品,主要面向欧美地区的客户,所以经常涉及到根据时区切换时间的问题.所以花点时间研究这块问题。
前提:数据库时间字段(datetime),入库时最好选择UTC时间。方便后期根据不同地区的客户进行时间的转换。
话不多说,直接上代码。
1.首先,sql server提供了GETUTCDATE 这个时间函数,可以获取当前utc时间。
2. .NET 中提供了TimeZoneInfo类,提供了一些方法用于时区的转换
3. 第三方的NetGet包:TimeZoneConverter
Codes:
using System;
using System.Collections.Generic;
using System.Text;
using TimeZoneConverter;
namespace DateTimeConvertDemo
{
public static class Extension
{
/// <summary>
/// 转化UTC时间为PST时间
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime ConvertToPST(this DateTime dateTime) {
TimeZoneInfo.ClearCachedData();
return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, "Pacific Standard Time");
}
/// <summary>
/// 转化PST时间为GMT(也就是UTC时间)
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime PSTConvertToGMT(this DateTime dateTime)
{
TimeZoneInfo.ClearCachedData();
TimeZoneInfo timeZoneSource = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
TimeZoneInfo timeZoneDestination = TimeZoneInfo.FindSystemTimeZoneById("UTC");
return TimeZoneInfo.ConvertTime(dateTime, timeZoneSource, timeZoneDestination);
}
/// <summary>
/// 转化PST时间为UTC时间
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime PSTConvertToUTC(this DateTime dateTime)
{
TimeZoneInfo.ClearCachedData();
return TimeZoneInfo.ConvertTimeToUtc(dateTime, TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
}
public static DateTime ToTimezone(this DateTime dt, string timezoneName = "America/Los_Angeles", bool isUtc = false)
{
try
{
TimeZoneInfo targetTimezone = TZConvert.GetTimeZoneInfo("Pacific Standard Time");
switch (timezoneName)
{
case "Europe/Paris":
targetTimezone = TZConvert.GetTimeZoneInfo("Romance Standard Time");// ("Central Europe Standard Time");
break;
case "Europe/London":
targetTimezone = TZConvert.GetTimeZoneInfo("GMT Standard Time");// ("W. Europe Standard Time");
break;
case "America/Los_Angeles":
targetTimezone = TZConvert.GetTimeZoneInfo("Pacific Standard Time");
break;
case "Asia/Tokyo":
targetTimezone = TZConvert.GetTimeZoneInfo("Tokyo Standard Time");
break;
default:
targetTimezone = TZConvert.GetTimeZoneInfo(timezoneName);
break;
}
var newtime = isUtc ? TimeZoneInfo.ConvertTimeFromUtc(dt, targetTimezone) : TimeZoneInfo.ConvertTime(dt, targetTimezone);
return newtime;
}
catch (Exception ex)
{
return DateTime.Now;
}
}
}
}
Example:
using System;
namespace DateTimeConvertDemo
{
class Program
{
static void Main(string[] args)
{
TestDateTime();
Console.WriteLine("Hello World!");
}
public static void TestDateTime() {
var pstDate1= DateTime.Now.ToTimezone();
var pstDate2 = DateTime.Now.ConvertToPST();
DateTime utcTime = DateTime.UtcNow;
DateTime pstTime = utcTime.ConvertToPST();
Console.WriteLine("pstDate1:"+pstDate1+ "\tpstDate2:"+ pstDate2+ "\tpstTime:"+ pstTime);
}
}
}
Result:
关于TimeZoneConverter更多的demo