Parsing custom format to DateTime - c#

I am trying to convert string to DateTime. Code look as follows:
DateTime.Parse("20131101T210705.282Z").ToShortTimeString()
I am getting format exception.
I tried providing following format "yyyyMMddTssmmhh.fffz" but received same exception. Code looked as follows
DateTime dt;
if (DateTime.TryParseExact("20131101T210705.282Z",
"yyyyMMddTssmmhh.fffz",
new CultureInfo("en-US"),
DateTimeStyles.None,
out dt))
return dt.ToShortTimeString();
In this case code doesn't parse the string.

Try this :
DateTime dt;
if (DateTime.TryParseExact("20131101T210705.282Z",
"yyyyMMddTssmmhh.fffZ",
new CultureInfo("en-US"),
DateTimeStyles.None,
out dt))
return dt.ToShortDateString() + " " + dt.ToShortTimeString();

This might be one way to parse.
var timeStamp = "20131101T210705.282Z";
var datetime = timeStamp.Split(new[] { 'T' ,'.'});
DateTime dt1;
if (DateTime.TryParseExact(datetime[0],
new string[] { "yyyyMMdd" },
new CultureInfo("en-US"),
DateTimeStyles.None,
out dt1))
{
Console.WriteLine(dt1.ToShortDateString());
}
DateTime dt2;
if (DateTime.TryParseExact(datetime[1],
new string[] { "ssmmhh" },
new CultureInfo("en-US"),
DateTimeStyles.None,
out dt2))
{
Console.WriteLine(dt2.ToShortTimeString());
}
Console.WriteLine(dt1.ToShortDateString() + " " + dt2.ToShortTimeString());
Console.ReadLine();

The format was simply incorrect. The timestamp value given doesn't clearly indicate where the hours are since all values (hours, minutes, and seconds) are less than 24. The following code works correctly.
DateTime.TryParseExact(value,
"yyyyMMddTHHmmss.fffZ",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt)
Given this proprietary format, the hours are in 24 hour format and come first. A test from this morning yielded the following value: 20131106T162733.032Z. I am able to test this proprietary format because we work for the same company. :)

Related

How can I get C# to recognize MM-dd-YY hh:mmtt as a valid datetime format?

I have a datetime string in the format "MM-dd-YY hh:mmtt". For example: 02-23-21 09:23PM. I am trying to convert this to a DateTime object in C#. I'm using DateTime.TryParseExact() but it keeps failing.
Here is how I'm converting it:
var myDateTime = new DateTime();
var success = DateTime.TryParseExact(
"02-23-21 09:23PM",
"MM-dd-YY hh:mmtt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out myDateTime
);
TryParseExact() keeps returning false and myDateTime keeps coming out {0001-01-01 12:00:00 AM}.
Can anyone see what I'm doing wrong?
You have an error in your year format - yy is correct one:
var success = DateTime.TryParseExact(
"02-23-21 09:23PM",
"MM-dd-yy hh:mmtt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out myDateTime
);
From the docs:
The "yy" custom format specifier represents the year as a two-digit number

How to convert datetime exactly what I am getting the output from client side

I have a variable as property like this:
DateTime? something;
something = Convert.ToDateTime(d1);
where d1 = '04/20/2020 12:50 PM';
I get a runtime error:
String was not recognized as a valid datetime
Then I tried this code:
something = DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", null);
and get a compile time error:
No overload for method 'TryParseExact' takes 3 arguments
Then I tried to convert it like by below too
something = DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt);
and got another compile-time error:
Cannot implicitly convert type bool to System.DateTime?
How to convert nullable datetime to getting datetime format?
See this
public static bool TryParseExact (string s, string format, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);
Parameters
s String A string containing a date and time to convert.
format String The required format of s.
provider IFormatProvider An object that supplies culture-specific
formatting information about s.
style DateTimeStyles A bitwise combination of one or more enumeration
values that indicate the permitted format of s.
result
DateTime When this method returns, contains the DateTime value
equivalent to the date and time contained in s, if the conversion
succeeded, or MinValue if the conversion failed. The conversion fails
if either the s or format parameter is null, is an empty string, or
does not contain a date and time that correspond to the pattern
specified in format. This parameter is passed uninitialized.
Returns Boolean true if s was converted successfully; otherwise,
false.
Exceptions ArgumentException styles is not a valid DateTimeStyles
value.
-or-
styles contains an invalid combination of DateTimeStyles values (for
example, both AssumeLocal and AssumeUniversal).
So we need to check the success or fail, and handle it.
DateTime? something;
if(DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
something = dt;
else
something = null;
This is the correct use of TryParseExact
public static void Main()
{
string d1 = "04/20/2020 12:50 PM";
if (DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt",
CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt));
Console.WriteLine("Date time OK: " + dt);
else
Console.WriteLine("Invalid Date time: " + d1);
}
TryParseExact return a bool, yout datetime object is dt
public static void Main()
{
string d1 = "04/20/2020 12:50 PM";
var result = DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt);
Console.WriteLine(dt);
}

Why DateTime.TryParseExact is not working?

I am reading date from Excel and stored it in a variable In_Date,
formats with which the date is to be compared is stored in Valid_Date_Formats
In_Date = "08/01/2020 00:00:00"
Valid_Date_Formats is an array which stores multiple date formats.
I am checking the format in if condition but it always fails.
If(DateTime.TryParseExact(In_Date, Valid_Date_Formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
DateTime_PlaceHolder))
What am I doing wrong here.
The input string has the following format: dd/MM/yyyy HH:mm:ss, which is missing from Valid_Date_Formats. (I'm assuming the 08 here is the day, because all your other formats start with the date part.)
The following returns the correct date:
DateTime.ParseExact("08/01/2020 00:00:00", new[] { "dd/MM/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.None)
In response to your comment: I'm not aware of a built-in method that would tell you which exact format string was used. If you really need to find out, I guess you could traverse the formats until you find a match:
string[] formats = new[] { "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss" };
string input = "08/01/2020 00:00:00";
string usedFormat = null;
DateTime date;
foreach (string format in formats)
{
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
usedFormat = format;
break;
}
}

How to parse the date time string including the milliseconds using c#?

I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.

CONVERT MM/DD/YYYY HH:MI:SS AM/PM to DD/MM/YYYY in C#

How can I convert MM/DD/YYYY HH:MI:SS AM/PM into DD/MM/YYYY using C# ?I am using C#2008.
Thanks
Use TryParseExact to parse to a DateTime, then ToString with a format string to convert back...
DateTime dt;
if (DateTime.TryParseExact(value, "MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out dt))
{
string text = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
// Use text
}
else
{
// Handle failure
}
As the time part is irrelevant, you can truncate that before parsing and re-formatting:
date = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture).ToString("dd'/'MM'/'yyyy");
Edit:
As your comment reveals that you don't want a string as result, you should not format the date into a string, just get the date as a DateTime value:
Datetime dbDate = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);
Now you can use the DateTime value in your code, wrapping it in a database driver type if needed.
If this is a DateTime object, you should be able to just select a different format.
If it is a string, use the following:
public string convert(string date){
string[] pieces = date.Split("/");
string day = pieces[1];
string month = pieces[0];
string year = pieces[2].split(" ")[0];
return day + "/" + month + "/" + year;
}

Categories