Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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
Posted
Updated 4-Sep-16 23:26pm

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.
 
Share this answer
 
No need to replace the '-' with '/'
C#
DateTime StartDate = DateTime.ParseExact(scheduleDates[0], "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
 
Share this answer
 
v2
Comments
abdul subhan mohammed 5-Sep-16 5:31am    
thanks alot!
Karthik_Mahalingam 5-Sep-16 5:32am    
Welcome
abdul subhan mohammed 5-Sep-16 9:57am    
Hi karthik, i'm getting date but with time. I just want short date, how can i do this,
please let me know. Thanks
Karthik_Mahalingam 5-Sep-16 9:58am    
Use .ToShortString ()
abdul subhan mohammed 5-Sep-16 10:03am    
public List<datetime> Scheduler
{
get { return ScheduleDates.Split(',').Select(item => DateTime.ParseExact(item, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString()).ToList(); //Error Cannot implicitly convert list<string> to list<datetiem>
}

set
{
ScheduleDates = ScheduleDates.Remove(ScheduleDates.Length - 1);
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900