Converting this string format to a valid DateTime? - c#

The string in question: "2003:12:14 12:01:44" (yyyy:MM:dd hh:mm:ss)
How would I be able to convert this to a valid datetime in C#? I tried Convert.ToDateTime(str), but to no avail.

Use the right DateTime format and supply DateTime.ParseExact with that format. Note that since your time doesn't show AM or PM, it may be safer to assume that it uses 24-Hr format (use capital HH) than 12-Hr AM PM (not hh) format. The following code should work:
string format = "yyyy:MM:dd HH:mm:ss"; //note: use HH not hh
var result = DateTime.ParseExact("2003:12:14 12:01:44", format, CultureInfo.InvariantCulture);
Check more on the available DateTime formats here (standard) and here (custom).

Convert.ToDateTime try to parse your string as a standard date and time format of your CurrentCulture settings. Looks like this string is not a standard format.
You can use DateTime.ParseExact for specify custom format.
var dt = DateTime.ParseExact("2003:12:14 12:01:44",
"yyyy:MM:dd hh:mm:ss",
CultureInfo.InvariantCulture);

Related

Change DateTime Format {"MM/dd/yyyy"} to {"dd/MM/yyyy"} and time should remain same in Unity

I want to change DateTime now to the Format {"MM/dd/yyyy"} using this code.
string.Format("{0:MM:dd:yyyy}", DateTime.Now)
and saving it.
after getting saved string I get DateTime in format {"MM/dd/yyyy"} . Now I want to convert it in another format so I can Parse to DateTime. when I try to parse MM/dd/yyyy to DateTime got an error
"FormatException: String was not recognized as a valid DateTime."
Thanks in Advance.
You can rather use DateTime.ParseExact which allows you to specify the exact date format you are expeting the input to have.
For example
var now = DateTime.Now;
Debug.Log(now.ToString("dd.MM.yyyy"));
var example1 = now.ToString("MM/dd/yyyy");
Debug.Log(example1);
var readTime1 = DateTime.ParseExact(example1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime1.ToString("dd.MM.yyyy"));
var example2 = now.ToString("dd/MM/yyyy");
Debug.Log(example2);
var readTime2 = DateTime.ParseExact(example2, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime2.ToString("dd.MM.yyyy"));
See Fiddle
The format is only relevant for display
If you save it in a C# DateTime variable, there is no "format" when saving it, this DateTime is a struct data type which is universal and not bound to any specific format
If you want to use a specific format for parsing, you can use:
// Parse date and time with custom specifier.
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
DateTime myDate = DateTime.ParseExact(dateString, format, provider);
You can use CultureInfo to optimize your format for you needs
If there is a need to save it as "MM/dd/yyyy", your should save it as string
best regards

c# convert yyyymmdd text to dd/MM/yyyy

I have some text in rows as yyyymmdd (eg: 20181211) which I need to convert to dd/MM/yyyy
I am using:
cashRow["BusinessDate"] = Convert.ToDateTime(row.Cells[ClosingDate.Index].Value.ToString()).ToString("dd/MM/yyyy");
I get the error "string was not recognized as a valid DateTime.
Any ideas where I am going wrong?
You'll need to use ParseExact (or TryParseExact) to parse the date:
var date = "20181217";
var parsedDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var formattedDate = parsedDate.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Here we tell ParseExact to expect our date in yyyyMMdd format, and then we tell it to format the parsed date in dd/MM/yyyy format.
Applying it to your code:
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
You have to use ParseExact to convert your yyyyMMdd string to DateTime as follows and then everything is okay.
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
As you already know the exact format of your input yyyyMMdd (eg: 20181211), just supply it to DateTime.ParseExact() and then call ToString() on the returned DateTime object.
string YourOutput = DateTime.ParseExact(p_dates, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Try this:
cashRow["BusinessDate"] = row.Cells[ClosingDate.Index].Value.ToString("dd/MM/yyyy");

How to define DateTime parse format for general date format with optional time part?

What is the right DateTime format to parse a date from string in general date format ("G") with optional time part ("d")?
I can have two types of dates:
"12/13/2012 6:30:00 PM"
"3/29/2013"
How to parse them in unified way?
Right now I'm trying to parse with "G" format and then if it not parsed with "d" format.
If your CurrentCulture supports MM/dd/yyyy h:mm:ss tt (I assume your LongTimePattern has h) and M/dd/yyyy (I assume your ShortDatePattern has M) as standard date and time format, using DateTime.TryParse(String, out DateTime) method can solve all your problems.
string s = "";
DateTime dt;
if (DateTime.TryParse(s, out dt))
{
// Your string parsed successfully.
}
If these formats doesn't standard date and time format for your CurrentCulture, using DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload can be the best choice because it takes formats part as a string array. That means, you can provide multiple formats and your string will be parsed with first successful match.
string s = "";
string[] formats = { "MM/dd/yyyy h:mm:ss tt", "M/dd/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(s, formats, CultureInfo.CurrentCulture,
DateTimeStyles.None, out dt))
{
// Your string parsed with one of speficied format.
}
Be careful when you parse string that have "/" custom format specifier. It has a special meaning of replace me with current culture or specified culture date separator. That means if your CurrentCulture's DateSeparator property is not /, your parsing operation will fail even if your string and formats are the same format.
Just use DateTime.Parse() or if you want to do a safe parse attempt DateTime.TryParse()
DateTime dt1, dt2;
dt1 = DateTime.Parse("12/13/2012 6:30:00 PM");
dt2 = DateTime.Parse("3/29/2013");
OR
DateTime.TryParse("12/13/2012 6:30:00 PM", out dt1);
DateTime.TryParse("3/29/2013", out dt2);
You only have to use DateTime.ParseExact() or provide the format if it differs from the accepted formats that DateTime.Parse() accepts, or if you only allow one particular format.

How to set/know DateTime class date format interpretion?

I have a particular loop where DateTime instances are to be generated. My problem is on how does the class interpret the input string.
The incoming input strings are of the format MM/dd/yyyy.
Suppose I have "1/17/2014", DateTime would interpret this as MM/dd/yyyy.
But if I have "6/5/2014", how will I be sure that DateTime will parse this with the format MM/dd/yyyy and not dd/MM/yyyy?
EDIT: Inputs may come with the month and/or day in one- or two-digit format.
Because the dates could come in either MM/dd/yyyy or M/d/yyyy then the overload that takes a string[] is the most appropriate:
var dt = DateTime.ParseExact(input,
new[] { "M/d/yyyy", "MM/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Now, regardless of the zero-padding it will work as expected.
Use the ParseExact function to specify the format :
DateTime d = DateTime.ParseExact("6/5/2014", "M/d/yyyy", CultureInfo.InvariantCulture);
If your input are in MM/dd/yyyy format, you will get 06/05/2014 instead of 6/5/2014. You will then have to use :
DateTime d = DateTime.ParseExact("06/05/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture);
Be sure of your input format if you don't want to have an exception.
take a look at DateTime.ParseExact, which will allow you to specifically match the string

Retaining MM/DD/YYYY format in String

I need to write date in MM/DD/YYYY format. From a Date Picker Control. I try to assign it to a DateTime variable. Before Writing it to a file I assign it to a string. I see the value stored in String variable is in DD/MM/YYYY format.
Below is assignment statement
DateTime startTime, endTime;
string startTimeDate = "";
startTime = Convert.ToDateTime(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"));
endTime = Convert.ToDateTime(dpEndTime.Value.ToString("MM/dd/yyyy HH:mm"));
startTimeDate = startTime.ToString("MM/dd/yyyy HH:mm");
startTimeDate = startTimeDate.Replace('-', '/');
I observe startTimeDate is stored as DD/MM/YYYY only. startTime is storing as MM/DD/YYYY format only. Please let me know if there is any other approach to correctly assign / convert the date values.
Thanks in Advance
Edit:
You are losing the original date in your Convert.DateTime() conversion, you have to apply the format string here as well e.g. using DateTime.ParseExact :
startTime = DateTime.ParseExact(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"),
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Instead of using Convert.ToDateTime(), try to use DateTime.ParseExact(string s, string format, IFormatProvider provider) when you can ensure the datetime format and want to ignore the system settings. MSDN Reference for the DateTime.ParseExact() method can be found here
You're converting DateTime to string, then you're converting it again to DateTime using Convert class. You're not preserving the format here cause DateTime is format agnostic. And default ToString conversion (used by debugger) is in your cause MM/DD/YYYY.
I usually use String.Format, ex
String.Format("{0:d/M/yyyy HH:mm:ss}", dpStartTime.Value);
To format dates as strings.

Categories

Resources