如何将javascript日期转换为C#? [英] How to convert javascript date to C#?

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

问题描述

大家好,



我想将javascript日期转换为c#。



在我的asp中.net web应用程序,我将值存储在Hiddenfields中。



这个hdn.value然后,我正在尝试转换为C#中的DateTime。



但是得到的错误是字符串不是正确的格式



例如: javascript的日期:2016-09-05





我的尝试:



 string [] scheduleDates = hdnScheduleDates.Value.Split(','); 
string dt = scheduleDates [0] .Replace( - ,/);
DateTime StartDate = DateTime.ParseExact(dt,dd / MM / yyyy,CultureInfo.InvariantCulture);





can请帮帮我吗?





谢谢

解决方案

你的日期和您尝试解析它的格式不匹配:

例如:来自javascript的日期:2016-09-05



 DateTime.ParseExact(dt,dd / MM / yyyy,... 



尝试更改格式为yyyy-MM-dd,它应该可以工作。

但我强烈建议使用TryParseExact - 它会返回一个成功/失败代码,而不是在格式化时不会抛出异常匹配。


无需用'/'替换' - '

 DateTime StartDate = DateTime.ParseExact( scheduleDates [ 0 ],  yyyy-MM-dd ,System.Globalization.Cultur eInfo.InvariantCulture); 


Hi Guys,

I want to convert javascript date to c#.

In my asp.net web application, i'm storing the values in Hiddenfields.

This hdn.value then, i'm trying to convert to DateTime in C#.

But getting the error as "String was not is proper format"

eg: date from javascript: "2016-09-05"



What I have tried:

string[] scheduleDates = hdnScheduleDates.Value.Split(',');
string dt = scheduleDates[0].Replace("-", "/");
DateTime StartDate = DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);



can any please help me?


Thanks

解决方案

Your date and the format you are trying to parse it as do not match:

eg: date from javascript: "2016-09-05"


DateTime.ParseExact(dt, "dd/MM/yyyy",...


Try changing the format to "yyyy-MM-dd", and it should work.
But I'd strongly suggest using TryParseExact instead - it returns a boll success/fail code instead of throwing an exception when the format doesn't match.


No need to replace the '-' with '/'

DateTime StartDate = DateTime.ParseExact(scheduleDates[0], "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);


这篇关于如何将javascript日期转换为C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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