我用UTC时间存储用户时间,当我显示它时,我需要将它转换为下午时间。如何将时间范围转换为下午或上午时间?
这里是例如在数据库中,我已经17:00:00转换至下午5:00
这里是我想出了到目前为止的代码,但它不工作
var time = DateTime.ParseExact(object.Time.ToString(), "HHmm", CultureInfo.CurrentCulture).ToString("hh:mm tt");
我用UTC时间存储用户时间,当我显示它时,我需要将它转换为下午时间。如何将时间范围转换为下午或上午时间?
这里是例如在数据库中,我已经17:00:00转换至下午5:00
这里是我想出了到目前为止的代码,但它不工作
var time = DateTime.ParseExact(object.Time.ToString(), "HHmm", CultureInfo.CurrentCulture).ToString("hh:mm tt");
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt");
回报05:00 PM
DateTime.ParseExact将返回日期时间
编辑:
包含的CultureInfo
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt", CultureInfo.GetCultureInfo("en-US"));
它取决于'CultureInfo.CurrentCulture'。检查:var time = DateTime.ParseExact(“17:00”,“HH:mm”,null).ToString(“hh:mm tt”,CultureInfo.GetCultureInfo(“es-ES”));'。 –
我的意思是,对于文化ES ES它不会显示AM/PM ...:-) –
@KirillPolishchuk:用这个扩展方法更新可能很好:public static string ToAMPM(this TimeSpan timespan) {DateTime dt = DateTime.ParseExact(“17:00”,“HH:mm”,null) ; var timeString = dt.ToString(“hh:mm tt”,System.Globalization.CultureInfo.GetCultureInfo(“en-US”)); return timeString; } – Lee
时间跨度是持续时间“17小时”,而不是时间。也许将此添加到日期(仅)并使用现有的日期时间格式选项? (虽然手表夏令)
即
string s = DateTime.Today.Add(duration).ToString(specifier);
不要忘记指定适当的文化,例如:CultureInfo.InvariantCulture
。
var time = DateTime.Now.ToString("h:mm tt", CultureInfo.InvariantCulture);
基于您的评论,首先转换TimeSpan
为DateTime
:
var dtUtc = DateTime.Now.ToUniversalTime();
dtUtc.AddHours(timeSpanObject.Hours);
dtUtc.AddMinutes(timeSpanObject.Minutes);
一旦它的一个DateTime
,你可以从UTC将其转换为本地时间:
var dtLocal = dtUtc.ToLocalTime();
只有w母鸡你显示它,你会包括AM/PM,如:
dtLocal.ToString("h:mm tt");
我只需要用我的TimeSpan显示静态HTML。所以在我看来,我用过,
DateTime.Today.Add(StartTime).ToString("%h:mm tt")
“StartTime”是我的TimeSpan,它将其转换为DateTime并显示它。现在我的时间显示为“3:00 PM”而不是“15:00”。 “%h”消除了1-9之间的前导零。
你有时间或UTC时间吗?这并不合适。什么是“ToString”并再次解析业务? – CodesInChaos