Convert string to mm/dd/yyyy datetime - c#

I'm trying to convert string which comes from textbox, for example in this format '03/24/2014' to DateTime. This is what I'm trying:
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "dd/MM/yyyy", us);
or
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "dd/MM/yyyy", null);
But no luck and I'm getting exceptions that the value cannot be casted as DateTime. How can I fix this problem?

03/24/2014 isn't a valid date in dd/MM/yyyy format (there are only 12 months in a year1).
Either change your format string to MM/dd/yyyy or use a valid date in your chosen format.
1: Or 13 months in some types of Calendar, but "en-US" uses the 12-month Gregorian calendar.

DateTime myDate = DateTime.ParseExact("24/03/2014", "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);

03/24/2014 has the day of the month as the middle component. That might seem strange, but that's how it's done in some parts of the world (mostly Northern America).
Thus, when specifying the format for parsing, you also have to put the day of the month (dd) in the middle:
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "MM/dd/yyyy", us);
Obviously, it is not possible to parse a text field that accepts both middle-endian (MM/dd/yyyy) and small-endian (dd/MM/yyyy) dates, because ambiguities like 01/02/2014 cannot be resolved automatically.

If the string is expressed in the format MM/dd/yyyy then
CultureInfo us = new CultureInfo("en-US");
dtAssemblyDate = DateTime.ParseExact(txtOperationSignatureDate.Value, "MM/dd/yyyy", us);
but I prefer to use DateTime.TryParse to avoid surprises...
if(DateTime.TryParse(txtOperationSignatureDate.Value,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dtAssemblyDate))
Console.WriteLine(dtAssemblyDate.ToShortDateString());

CultureInfo us = new CultureInfo("en-US");
DateTime dt = Convert.ToDateTime(txtOperationSignatureDate.Value, us.DateTimeFormat);
Whatever DateTimeFormat you require, you just need to pass corresponding culture with it.

Try using
string date = textbox.Value;
DateTime dt = Convert.ToDateTime(date);

Related

How to convert to system datetime format from a string?

I need to convert a string datetime format to a DateTime field which should be in system Datetime format?
I've tried Convert.ToDateTime, DateTime.Parse, DateTime.ParseExact but all of them convert to dd-MM-yyyy HH:mm:ss format.
My string is in yyyy-MM-dd HH:mm format.
I was trying TryParseExact and specifying the culture also but I just couldn't understand that how it works. Below is the code that I am trying and my item.CreationDate is in "yyyy-MM-dd HH:mm" format
DateTime dateTime;
bool isSuccess1 = DateTime.TryParseExact(item.CreationDate, "yyyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTime);
DateTime result = dateTime;
Thanks in advance.
Can it be this easy? - yyyyy-MM-dd HH:mm has 5 ys in your example, not 4.
When you convert a string to DateTime you must state what format the input is in (as you have). If the conversion succeeded the DateTime object will hold the data for all the date parts (years, months, days etc.) and if you want to view them as a date again you must state what format you want to see them in. When using DateTime.TryParseExact it's worth noting that if the conversion fails it will set the value to the DateTime.MinValue.
There are various ways of showing the date again. The most common is stating the custom format for the date as a string. Another way is to use a standard format.
var creationDate = "2020-04-13 13:23";
DateTime.TryParseExact(creationDate, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateTime);
var myCulture = new CultureInfo("en-GB");
if(dateTime > DateTime.MinValue)
{
Console.WriteLine("Your custom format date is: " + dateTime.ToString("yyyy-MM-dd HH:mm"));
Console.WriteLine("Your standard format date is: " + dateTime.ToString("g", myCulture));
}
When you put this into a console app the results are like this:
With some of the standard format ones you will need to define the culture as it will be different for something like the en-US compared to something like zh-CN. In my case I used 'en-GB'. Here's a list of the accepted culture codes.

Parse string to DateType ASP.NET C# exception - The string was not recognized as a valid DateTime

So I have a date which is in this format. My goal is to add 7 days to this string startdate and post it into a database as a string. However, I have to convert it to datetime to allow me to add days to it. I am reading startdate from a database but this is what it looks like.
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm tt", culture);
// It is breaking on the above line with the error - The string was not recognized as a valid DateTime.
DateTime endtime2 = starttime2.AddDays(+7);
Anyone able to help me solve this issue? I am new to C# and would appreciate any help at all..
Thank you
You have specified wrong format actually. You should be specifying the following format:
"dd-MM-yyyy hh:mmtt"
as your date is in format :
"10-03-2018 03:15PM"
Assuming that the first number us for day and second is for month, otherwise you can swap those.
You can see more details on the usage of ParseExact here.
Try this:
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "dd-MM-yyyy hh:mmtt", culture);
no space between mm and tt. also this is 12 hours format so hh
I think this will help you
public static DateTime AddDaysToMyDate(string date)
{
return DateTime.ParseExact(date, "dd-MM-yyyy hh:mmtt", new CultureInfo("en-US", true)).AddDays(7);
}
Use it as
DateTime newDateTime = AddDaysToMyDate("10-03-2018 03:15PM");

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

I am trying to convert DateTime format to yyyy-MM-dd format and store it to DateTime object. But it gives me the System DateTime format that is MM/dd/yyyy.
I am using following code to convert.
string dateTime = DateTime.Now.ToString();
string createddate = Convert.ToDateTime(dateTime).ToString("yyyy-MM-dd h:mm tt");
DateTime dt = DateTime.ParseExact(createddate, "yyyy-MM-dd h:mm tt",CultureInfo.InvariantCulture);
but non of the above line converts into the specified format.
Can any one help to solve this.
I am getting the DateTime from one application and passing this object to other application and That application is storing that date into MySql's DateTime field which is in the format "yyyy-MM-dd".
This is why I have posted this question.
Project 1 has class from that I am getting the date.
and the processor class which is the middle ware of the application it processes the DateTime format to convert in specific format. And passes to the Other project which consumes the DateTime and stores that in the MySql field.
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.
We can use the below its very simple.
Date.ToString("yyyy-MM-dd");
Have you tried?
var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// "2013-10-10T22:10:00"
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern);
// "2013-10-10 22:10:00Z"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)
Also try using parameters when you store the c# datetime value in the mySql database, this might help.
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
I know this is an old thread, but to all newcomers, there's a new simplified syntax (Intellisense highlighted it for me, not sure how new this feature is, but my guess is .NET 5.0)
DateTime date = DateTime.Now;
string createdDate = $"{date:yyyy-MM-dd}";
Maybe doesn't look simplified in this example, but when concatenating a long message, it's really convenient.
GetDateTimeFormats can parse DateTime to different formats.
Example to "yyyy-MM-dd" format.
SomeDate.Value.GetDateTimeFormats()[5]
GetDateTimeFormats
Try this!
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Ticks)
The culture invariant way, best practice:
DateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)

C#: How to convert string to date accordingly to the giver format?

I have 2 strings: one is date value like "20101127", the second is format "yyyymmdd". How could I extract the date from the value using the given format?
Thanks
Use DateTime.ParseExact:
DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", null);
null will use the current culture, which is somewhat dangerous. You can also supply a specific culture, for example:
DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", CultureInfo.InvariantCulture);
Use DateTime.ParseExact(). Note that month is MM, not mm.
var dateValue = DateTime.ParseExact("20101127", "yyyyMMdd",
CultureInfo.InvariantCulture);
Use the ParseExact method.

Date format issue between in app and windows with c#

I want to convert a string to datatime. Here is my code:
DateTime? dt = null;
dt = DateTime.Parse(postdate[i]);
It works only for dd/mm/yyyy, not work for mm/dd/yyyy because on my computer the date format is set as dd/MM/yyyy in Control Panel.
So if I want to use the application always accept valid format mm/dd/yyyy, no matter the windows date format setting is. How to implement this in c# code?
I think this should work:
DateTime? dt = null;
dt = DateTime.ParseExact(postdate[i], "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);
You could do something like this:
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime myDateTime = DateTime.Parse(myDateTimeValue, culture);
Instead of parsing with the default culture (which is based on the computer's regional settings) it will parse with the US culture which uses MM/dd/YYYY
#JDunkerley's response is on the right track, but:
the format specifier for a 2-digit month is MM not mm.
using CultureInfo.CurrentCulture won't correctly parse a string containing slash separtors if you are running under a culture that uses a different separator (for example: the culture de-DE will expect a period separator.
This will work:
dt = DateTime.ParseExact(postdate[i], "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);

Categories