如何字符串转换为当地的日期时间? [英] How to convert string to local Date Time?

查看:227
本文介绍了如何字符串转换为当地的日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换格式的字符串:

I am trying to convert a string of this format:

MM/dd/yyyy HH:mm

的输入是从美国的数据库,因此,即: 09/20/2010 14:30

The input is from a US database, so, i.e.: 09/20/2010 14:30

我知道,我的字符串始终是美国时间,但是当我展示它,我需要它转换成当地的时间,因此该字符串应该变成:

I know that my string is always US time but when I display it, I need to translate that into the local time, so that string should be turned into:

09/20/2010 19:30 (for UK for instance)

我尝试了一些事情,但似乎没有给我正确的解决方案,当我运行一个美国机上VS英国或Ge机 我想:

I tried a few things but nothing seems to give me the correct solution when I run on a US machine vs a UK or Ge machine I tried:

CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", new CultureInfo("en-US"));

他们都在当地工作(美机),但他们的时间转换为本地时间欧洲的机器上。

They all work locally (US machine) but they don't convert the time to local time on a European machine.

谢谢 托尼

推荐答案

试试这个 - 它在GB当地时间(输入美国格式)转换为格林尼治标准​​时间,然后打印/ DE格式

Try this - it converts local time (input in US format) to GMT and then prints in GB/DE format.

var zones = TimeZoneInfo.GetSystemTimeZones();    // retrieve timezone info
string value = "09/20/2010 14:30";

DateTime CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm",    
    new CultureInfo("en-US"));
DateTime FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, 
    TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), 
    TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"));
string output = FinalDttm.ToString(new CultureInfo("en-GB"));

FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, TimeZoneInfo.Local, 
    TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));
output = FinalDttm.ToString(new CultureInfo("de-DE"));

输出为,依次为:

Output is, in turn:

20/09/2010 19:30:00

20/09/2010 19:30:00

2010年9月20号20点30分○○秒

20.09.2010 20:30:00

这篇关于如何字符串转换为当地的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆