convert date string to datetime - c#

I have date string in format dd-MMM-yyyy and want to convert this to datetime, when I use below code
DateTime.ParseExact("20-Oct-2012", "yyyy-MM-dd HH:mm tt", null)
it causing an error
String was not recognized as a valid DateTime.
When I modify above code
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null)
then I got date time in format (mm/dd/yyyy) : 10/20/2012 12:00:00 AM
But I need it should be converted in yyyy/mm/dd format. Please help me in this regard.

You should try this
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")
For further reading on formats Check This

You need to distinguish between two separate concerns: that of parsing your original string into an abstract DateTime representation, and that of converting the latter back into another string representation.
In your code, you're only tackling the former, and relying on the implicit ToString() method call (which uses the system's current locale) to convert it back to string. If you want to control the output format, you need to specify it explicitly:
// Convert from string in "dd-MMM-yyyy" format to DateTime.
DateTime dt = DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null);
// Convert from DateTime to string in "yyyy/MM/dd" format.
string str = dt.ToString("yyyy/MM/dd");
Also note that the mm format specifier represents minutes; months are represented by MM.
Edit: 'Converted date contain value "10/20/2012 12:00:00 AM".' Be careful what you mean by that. The constructed DateTime value contains an abstract representation of the parsed date and time that is independent of any format.
However, in order to display it, you need to convert it back into some string representation. When you view the variable in the debugger (as you're presumably doing), Visual Studio automatically calls the parameterless ToString() method on the DateTime, which renders the date and time under the current culture (which, in your case, assumes the US culture).
To alter this behaviour such that it renders the date and time under a custom format, you need to explicitly call the ToString(string) overload (or one of the other overloads), as I've shown in the example above.

You could try this instead :
Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")
Hope this will help !!

Related

Not able to convert the datetime stored as a string to Datetime within a IList

I'm working on an WebApi which receives the data from database using Lambda and storing in a IList. The output I'm getting has a dataformat as "2018-04-20T14:39:20.01". But I want to show the date format as "20-Apr-2018 / 02:39:20 PM".
Once i get the output, I'm manipulated the date and converted to the format which I wanted that are stored as a string.
Now when I'm trying to send that data back to the IList, am getting error saying that the String is not recognized as a valid datetime.
string val = statusSourceType1[0].updatedDate.Value.ToString("dd-MMM-yyyy hh:mm:ss tt").ToString();
#1
statusSourceType1[0].updatedDate = DateTime.Parse(val);
#2
statusSourceType1[0].updatedDate = DateTime.ParseExact(val, "dd-MMM-yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
#3
statusSourceType1[0].updatedDate = DateTime.ParseExact(val, "dd-MMM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces);
In the above code, first line converts the dateformat from 2018-04-20T14:39:20.01 to 15-Apr-2018 12:23:21 PM.
Once the conversion is done, I want to convert the string value into datatime and pass with the output since my UI is expecting the datetime and not string.
While converting the string to datetime, either Am getting the runtime error "String is not recognized as a valid datetime" or the datetime format gets back to its original state.
Please help me with this.
"...datetime stored as a string..."
There's your problem right there.
You are working in a WebApi and your UI is expecting a DateTime, not a string. So why do you bother to convert the date to string and back?
DateTime does not have a display format - only string representations of it does.
Just send the UI an instance of the DateTime struct and let the UI handle the display format - that's the UI's responsibility, not the server.
try setting culture if you need
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
then try
dt.ToString("dd/MMMM/yyyy"); //or whichever
As your comment. Answer simple question, if you set 1112018 as date using ddmmyyyy how can you expect to get the conversion working back to datatime. You app design is not right, let the View do the formatting and pass the dt obj
OR
make you View to expect string version of dt

DateTime.ParseExact doesn't work for "yyyy-MM-dd HH:mm:ss"

I have System.DateTime.Now stored in a variable called StartDate (variable is of type DateTime?).
I am converting it to string as below:
string temp = StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
Now the temp has value in "yyyy-MM-dd HH:mm:ss".
Now I want to again convert string temp to DateTime so, I am doing as below:
DateTime.ParseExact(temp,"yyyy-MM-dd HH:mm:ss",null)
but this doesn't work.
It always returns date in a same format as System.DatTime.Now. It should return value in "yyyy-MM-dd HH:mm:ss" format.
A value of type DateTime doesn't have a particular format. That date-and-time is stored as a couple of integer values (not one for each component, but much more compact).
When you parse a string, that date represented in that string is stored as those integers.
Only when you do a .ToString() (possibly with some format) you get a string representation of that date in a particular format.
When you hover over the DateTime value in the debugger, you see the result of a plain .ToString(), using some specific current culture.
The difference between Parse and ParseExact is that Parse tries several formats (and may fail on a string like "2/3/2017" - FEB 3rd or 2nd MAR?) while with ParseExact you supply one or more formats yourself. In both cases you end up with a value of the same DateTime type.

Error converting DateTime to string format yyyy-MM-dd

I'm trying to convert some DateTime values to string format yyyy-MM-dd. The problem is i only need the date but in my case model.StartDate contains both date and time. When declaring model.StartDate as string "start" looks like this: 4/1/2014 12:00:00 AM. I get this error when trying to parse:
System.FormatException was unhandled by user code Message=String was
not recognized as a valid DateTime.
My best guess is that the error occurs because string contains both Date and Time but i could be wrong. If i explore model.StartDate further i can also find Day, DayOfTheWeek etc. Is this the right approach? I just want to convert model.StartDate to string "start" with format yyyy-MM-dd.
Heres my code:
string start = model.StartDate.ToString();
model.StartDate = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture);
string end = model.EndDate.ToString();
model.EndDate = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Dunno what the problem is, might be that start contains time? I have no idea.
The model.StartDate and model.EndDate are DateTime properties from the view model:
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.StartDate")]
[UIHint("DateNullable")]
public DateTime? StartDate { get; set; }
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.EndDate")]
[UIHint("DateNullable")]
public DateTime? EndDate { get; set; }
EDIT:
Iv'e uploaded a image here showing the actual output i'm getting in the debugger:
https://imageshack.com/i/1n51u2p
Thank you
You are converting the dates to string but you don't specify the format. Try
string start = model.StartDate.ToString("yyyy-MM-dd);
ToString() uses the current thread's Culture format to convert the date to a string, including the time. The format used is G, the general date and time format.
Just for this format, you don't need to specify CultureInfo.InvariantCulture because there isn't anything culture specific. A common gotcha with the yyyy/MM/dd format though is that some cultures use - as the date specifier, and / is the date placeholder. In such a case you would have to use:
string start = model.StartDate.ToString("yyyy-MM-dd,CultureInfo.InvariantCulture);
UPDATE
From the comments, it seems that model.StartDate and model.EndDate are not DateTime objects but strings with a specific format that include a time element.
What you are actually trying to do is parse the original string to a DateTime object, then format this object to the new format string:
var date=DateTime.ParseExact(model.StartDate,"M/d/YYYY HH:mm:ss tt",
CultureInfo.InvariantCulture);
model.StartDate=date.ToString("yyyy-MM-dd",CultureInfo.InvariantCulture);
assuming the string the value "4/1/2014 12:00:00 AM" for April 1, 2014
You appear to be misunderstanding how ParseExact works (or actually what it does). Parsing, in general, is the process of taking data of type X and converting it to type Y - in the context of DateTime this means converting a date string to a DateTime instance. This is completely different to what you are trying to do which is formatting a DateTime instance.
Given you already have the date you don't need to parse anything, all you need to do is format the date
model.StartDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is important when working with fixed formats because you want to make sure you aren't culture aware i.e. the format you specify is exactly how you want it to display in all cultures.
Use the .Date property of a DateTime to get only the Date part. Your ToString() will also yield different results based on the current culture meaning that while your ToString() and then TryParse might work for you right now, it will break in other countries.
You can use ToString() overload to specify a specific format. Different formats can be found here

remove time from date and print only date in datetime format

i have date stored in a string format as follows: "2014-03-12"
im passing this to a database which accepts the date as datetime.
im converting the string date to datetime format as follows:
DateTime StartDates = Convert.ToDateTime(StartDate);
but the time gets appended along with the date as "2014-03-12 12:00:00:00"
can anyone tel me how to send only the date leaving out the time.
i want the final date to be still in datetime format only but with time part cut off
DateTime is irrespective of the format. Formatting is only useful for presentation purpose. A DateTime object will have a Date part and Time part. When you try parsing your string "2014-03-12", it doesn't have a Time part, so in the parsed object, Time is set to 00:00:00.
If you just want to to display date then you can use DateTime.ToShortDateString method or use a custom format like:
string formattedDateString = StartDates.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
If you're happy with the date part, you may simply return the Date property of the DateTime conversion result:
DateTime StartDates = Convert.ToDateTime(StartDate).Date;
I should mention that using Convert.ToDateTime puts you at the mercy of the process current culture date format though, so you probably want to use the ParseExact or ToString method like the other answers suggests, with the appropriate format and culture instance.

C# Date Conversion From Euro Time To en-US Time Needed For Date Calculations

I have a date that is entered through the system (from a database) as dd/mm/yy I need to programmatically convert the date to en-US format to mm/dd/yyyy so that I can do some date calculations within the code. The code that I have so far is:
String myJames = "25/04/13" // Date String comes in as non-US date
String myJames2 = System.DateTime.Today.ToString(myJames); // I think the problem is here
DateTime d1 = Convert.ToDateTime(myJames2);
DateTime d2 = DateTime.Now;
TimeSpan t = d2 - d1;
double NrOfDays = t.TotalDays;
I know this is not completely correct, especially in the first few lines. Any help getting the dates into one en-US format for effective comparisons would be greatly appreciated.
Just to check I understand your question. You have a date as a string and you want to convert that string into a datetime so you can use it in a calculation? And your problem is that the string isn't in the format that the locale the code is running in would use?
In which case use DateTime.ParseExact.
DateTime d1 = DateTime.ParseExact(myJames,"dd/MM/yy");
This line of code would replace your line declaring and assigning d1. The line assigning to myJames2 can be removed as it isn't needed.
Everytime you convert from or to a string, culturesettings are involved.
So.. if you are converting a DateTime to string, and your culture is en-US, it will automatically converted to: MM/dd/YYYY.
This is also true for converting back. If you convert a string back to a DateTime, the culturesettings are used to see what format the string is in.
Teh culture settings are always: Thread.CurrentThread.CurrentCulture.
Most conversion functions allow to override the format (like "MM/dd/yyyy") and/or the culture. So you can create your own culture and use this during conversions.
You say the database uses dd/MM/yy, but normaly a DateTime in a database is not formatted, it is just a binary value. Or is it stored as a text? If it is stored as a text, than you should ALWAYS convert it to a DateTime using the correct culture or format.

Categories