-2

I have datetime value="11/03/2018 12:00:00 ص" I want to format this to be "11-03-2018" how to make this, and i want this value to be datetime, I tried using DateTime.Parse and ParseExact, but with errors

thanks

Dev Net
  • 1
  • 3
  • 1
    A DateTime represents an instant in time, it does not have a format. It's only when you use it (in a control for example) that the formatting comes into it. Are you converting it to a string? Can you show your code? – Chris Carr Mar 11 '18 at 18:58
  • You should definitely show your code. – Francesco B. Mar 11 '18 at 19:17

3 Answers3

1

You can format your datetime variable as a string using the ToString(string format) method overload. You can then set a custom format by specifying the format string so...

DateTime date = DateTime.Now;

Console.WriteLine(date); //3/11/2018 3:04:02 PM

string format = "M-dd-yyyy";

Console.WriteLine(date.ToString(format)); //3-11-2018

Check this link https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netframework-4.7.1#System_DateTime_ToString_System_String_

Ecordero
  • 71
  • 2
  • 6
0
DateTime value = "11/03/2018 12:00:00 ص";

var date = value.Date;

follow this thread for more information How to remove time portion of date in C# in DateTime object only?

0

The issue is with the trailing ص character in your string. I am not sure what this means but it causes the DateTime.Parse() function to not recognise the string as a date. I would suggest using a regex to remove just the date portion of the string, or if you know the string is always in the same format you can just take the first 19 characters and use DateTime.Parse() on that.

Alternatively if the character is something used in dates you can look into DateTime.ParseExact, which allows you to parse a format and culture info into it, you may be able to find a culture info that supports the format.

ZSOR
  • 45
  • 6