Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c# - unable to parse a string of this format "1/29/2020 12:00:00 AM" into a valid DateTime

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'"));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"].

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...