Date format issue between in app and windows with c# - 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);

Related

Convert to DateTime from a string '10-April-2020'

Looking for assistance in converting a date string i receive from a web form, where the format will be something like "10-April-2020". I need to save this into the database in the US date format "yyyy-mm-dd" so that the example date provided would go in as '2020-04-10'.
This is what I have so far, which complains that it is not a valid datetime.
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateExpires = DateTime.ParseExact(LicenseExpiry, "yyyy-MM-dd", culture);
I have also tried the following which also fails.
DateTime dateExpires;
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
if (DateTime.TryParseExact(LicenseExpiry, "yyyy-MM-dd", culture, DateTimeStyles.None, out dateExpires))
{
// Do something
}
Can anyone help with either of the attempts to see what went wrong? I am not allowed to change the Ui/Form to do any client side date manipulation either, and so my solution needs to be done in the C# code behind file.
MM means the month number (from 01 through 12)
To parse 10-April-2020, you
need MMMM, see
Custom date and time format strings
The "MMMM" custom format specifier represents the full name of the month

Adding two dates to eachother

string final = Convert.ToString(DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration));
Hi, I use the above code to add two date's to eachother. It do work very well on Windows and returns the required format yyyy-MM-dd HH:mm:ss in a correct fashion. HOWEVER, when on Linux building with Mono it returns the following format dd/MM/yyyy HH:mm:ss which is not what I want.
How can I specify that I ONLY want the first formatting and nothing else? I tried playing around with ParseExact but it did not do very well. What I've heard ParseExact should not really be needed for this?
Here is a example of input:
string date = "2014-10-30 10:00:04"; // On windows
string duration = "05:02:10"; // duration to be added to date
Greetings.
Use ToString("yyyy-MM-dd HH:mm:ss") instead of Convert.ToString.
string date = "2014-10-30 10:00:04";
string duration = "05:02:10";
DateTime dt1 = DateTime.Parse(date, CultureInfo.InvariantCulture);
TimeSpan ts = TimeSpan.Parse(duration, CultureInfo.InvariantCulture);
DateTime dtFinal = dt1.Add(ts);
string final = dtFinal.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Convert.ToString uses your current culture's date separator, use CultureInfo.InvariantCulture.
Read: Custom Date and Time Format Strings
You can use the ToString() Method of the DateTime object.
var dt = DateTime.Now;
dt.ToString("yyyy-MM-dd HH:mm");
Using your code:
string _final = (DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration)).ToString("yyyy-MM-dd HH:mm:ss");

Convert string to mm/dd/yyyy datetime

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);

Converting System Date Format to Date Format Acceptable to DateTime in C#

How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}

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)

Categories