无法解析这种格式的字符串“1/29/2020 12:00:00 AM";转换为有效的日期时间 [英] unable to parse a string of this format "1/29/2020 12:00:00 AM" into a valid DateTime

查看:30
本文介绍了无法解析这种格式的字符串“1/29/2020 12:00:00 AM";转换为有效的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 SVC 服务,当我在本地运行它时,我得到的日期字段如下 30/01/2020 00:00:00 并且我将此字符串解析为 DateTime 如下 (DateTime.ParseExact(i["ProjectLastUpdate"].ToString(), "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture).ToString("yyyy'-'MM'-'dd'T'00':'00':'00'Z'")),因为我的本地机器使用英国区域设置.但是当我在 Azure Web 应用程序中托管服务时,我开始接收如下日期字符串:1/29/2020 12:00:00 AM,并且该服务将引发此异常 上面代码中的字符串未被识别为有效的日期时间".那么有人可以就此提出建议吗?我可以在本地机器和 azure 上标准化日期格式吗?我也可以强制我的代码在两种环境下都可以工作吗?

I am working on a SVC service, and when I run it locally I get the Date field as follow 30/01/2020 00:00:00 and I parse this string to be a DateTime as follow (DateTime.ParseExact(i["ProjectLastUpdate"].ToString(), "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture).ToString("yyyy'-'MM'-'dd'T'00':'00':'00'Z'")), since my local machine uses the United Kingdom regional setting. But when I host the service inside an Azure Web App, I start receiving the date string as follows: 1/29/2020 12:00:00 AM, and the service will raise this exception "String was not recognized as a valid DateTime" on the above code. So can anyone advice on this please? Can I standardize the date format on both local machine and azure? Also can I force my code to work on both environments?

这是我在服务中的完整代码:-

Here is my full code, inside the service:-

using (ClientContext context = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
{
    CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml = string.Format("<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>{0}</Value></Eq></Where></Query></View>", listItemID);
    ListItemCollection collListItem = context.Web.Lists.GetByTitle("Project Update System").GetItems(camlQuery);
    context.Load(collListItem);
    foreach (ListItem i in collListItem)
    {
        var mydate = (DateTime.ParseExact(i["ProjectLastUpdate"].ToString(), "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture).ToString("yyyy'-'MM'-'dd'T'00':'00':'00'Z'"));

推荐答案

i["ProjectLastUpdate"] 的值已经一个 DateTime>,因此无需将其转换为字符串然后再解析回来.所以你可以使用一个简单的类型转换:

The value of i["ProjectLastUpdate"] already is a DateTime, so there's no need to convert it to a string and then parse it back. So you can use a simple typecast:

var mydate = (DateTime) i["ProjectLastUpdate"].

这篇关于无法解析这种格式的字符串“1/29/2020 12:00:00 AM";转换为有效的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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