C# parse DateTime String to time only - c#

I am new to C# and I have a string like "2021-06-14 19:27:14:979". Now I want to have only the time "19:27:14:979". So do I parse the string to a specific DateTime format and then convert it back to a string or would you parse or cut the string itself?
It is important that I keep the 24h format. I don't want AM or PM.
I haven't found any solution yet. I tried to convert it to DateTime like:
var Time1 = DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss:fff");
var Time2 = Time1.ToString("hh:mm:ss:fff");
But then I lost the 24h format.

Your code is almost working, but ParseExact needs two additional arguments and ToString needs upper-case HH for 24h format:
var Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None);
var Time2 = Time1.ToString("HH:mm:ss:fff");
Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#uppercase-hour-h-format-specifier
Instead of passing null as format provider(means current culture) you might want to pass a specifc CultureInfo, for example CultureInfo.CreateSpecificCulture("en-US").

You can just split it at the blank and take the last part like this
var timestamp = "2021-06-14 19:27:14:979";
var timePart = timestamp.Split(' ')[1];
in your case that seems easier than parsing into a DateTime and back into a string.

Related

C# Datetime.ParseExact for a parsing a string containing UTC text

I have a date time string that looks like this:
13.08.2014 17:17:45.000 UTC-60
I am trying to parse it into a C# date time object but it is not working as I expected.
Here is what I tried:
DateTime.ParseExact(dateToParse, "dd.MM.yyyy hh:mm:ss.fff Z", CultureInfo.InvariantCulture);
DateTime.ParseExact(dateToParse, "dd.MM.yyyy hh:mm:ss.fff UTC", CultureInfo.InvariantCulture);
DateTime.ParseExact(checkInDate, "dd.MM.yyyy hh:mm:ss.fff", CultureInfo.InvariantCulture);
They all return same error
{"String was not recognized as a valid DateTime."}
Some of the existing questions like this did not help either.
Any suggestions?
First, your main problem there with parsing is that your're using hh for 24h format. That should be HH. This should work:
DateTime.ParseExact("13.08.2014 17:17:45.000", "dd.MM.yyyy HH:mm:ss.fff", null, System.Globalization.DateTimeStyles.AssumeUniversal)
As for the UTC part, that's not standard format, so I suggest you to create a helper method that splits this string in 2, parse the first part as provided above, and parse the number after UTC and either add that to your DateTime:
myDate.AddMinutes(Int32.Parse("-60"))
Or create a DateTimeOffset. In either case, you must parse them individually.
How much control do you have over the time format.
.Net datetime parsing expects 2 things that are wrong with the current time format that you are trying to parse:
First, you have 24 hour time, so in your format you must use HH for hours, the lower case hh implies that the hours will be 12 hour format.
The UTC issue is another one that will require you to modify the string first, .Net expects timezone information in the form of HH:mm, so the following string and conversion will work, notice the key differences
var dateToParse = "13.08.2014 17:17:45.000 -01:00";
var value = DateTimeOffset.ParseExact(dateToParse, "dd.MM.yyyy HH:mm:ss.fff zzz", CultureInfo.InvariantCulture);
Use DateTimeOffset to maintain the TimeZone information
HH to map the hours
zzz to map the timezone information
So, to address you question, how can we parse the string into a format that we can then use to parse into a date time:
dateToParse = "13.08.2014 17:17:45.000 UTC-60";
string utc = null;
if (dateToParse.Contains("UTC"))
{
var tokens = dateToParse.Split(new string[] { "UTC" }, StringSplitOptions.None);
dateToParse = tokens[0];
utc = tokens[1];
int minutes = int.Parse(utc);
var offset = TimeSpan.FromMinutes(minutes);
bool negative = offset.Hours < 0;
dateToParse += (negative ? "-" : "") + Math.Abs(offset.Hours).ToString().PadLeft(2,'0') + ":" + offset.Minutes.ToString().PadLeft(2,'0');
}
var value = DateTimeOffset.ParseExact(dateToParse, "dd.MM.yyyy HH:mm:ss.fff zzz", CultureInfo.InvariantCulture);
To be honest, that was more complicated than I thought, there might be some regex expressions that might help, but this first principals approach to manipulating the string first works with your string.
Finally, now that we have a DateTimeOffset value, you can easily convert this into any local or other timezone without too much hassel, if you need to:
var asUtc = dateValue.UtcDateTime;
var asLocal = dateValue.LocalDateTime;
var asSpecific = dateValue.ToOffset(TimeSpan.FromHours(10)).DateTime;

How do I format a DateTime in a different format?

I have a string representing a date in a certain format, that I wish to format differently. Someone told me to use DateTime.(Try)ParseExact, so I did:
var dateString = "2016-02-26";
var formatString = "dd/MM/yyyy";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
You see, I want to format the date as dd/MM/yyyy, so 26/02/2016. However, this code throws a FormatException:
String was not recognized as a valid DateTime.
How can I format a DateTime differently?
First of all, DateTimes have no format. A DateTime holds a moment in time and a flag indicating whether that moment is Local, Utc or Unspecified.
The only moment a DateTime gets formatted, is when you output its value as a string.
The format string you provide to (Try)ParseExact is the format that the date(time) string to parse is in. See MSDN: Custom Date and Time Format Strings to learn how you can write your own format string.
So the code you're looking for to parse that string is this, and again, make sure the format string matches the format of the input date string exactly:
var dateString = "2016-02-26";
var formatString = "yyyy-MM-dd";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
Now parsedDate holds a DateTime value that you can output in your desired format (and note that you'll have to escape the /, as it'll be interpreted as "the date separator character for the current culture", as explained in above MSDN link):
var formattedDate = parsedDate.ToString("dd\\/MM\\/yyyy");
This will format the date in the desired format:
26/02/2016
You can use this for String date
DateTime.ParseExact(dateString, format, provider);
and for provider value
CultureInfo provider = CultureInfo.InvariantCulture;
as mentioned in Microsoft documentation

Converting string to valid DateTime

I know there are allot of questions regarding this, but I've been trying all day to get this conversion to work and have had no luck when applying the answers to the same question posted here. Every time I try to Parse the string to a DateTime, I get a "String was not recognized as a valid DateTime" exception. If I use Convert.ToDateTime, I can get a Date back from my string, but I need the hh:ss as well.
Here is my simplified code that is ruining my day:
var test = "2015-05-08T05:00Z";
DateTime testTime = new DateTime();
//testTime = Convert.ToDateTime(test);
testTime = DateTime.ParseExact(test, "mm/DD/yyyy HH:ss",
System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(testTime);
Why is this string not recognized as a valid DateTime when trying to convert?
All help is appreciated
Try this...
var test = "2015-05-08T05:00Z";
DateTime testTime = new DateTime();
testTime = DateTime.Parse(test, null, System.Globalization.DateTimeStyles.RoundtripKind);
Console.WriteLine(testTime);
Console.ReadLine();
Or even with DateTime.ParseExact()
var test = "2015-05-08T05:00Z";
DateTime testTime = new DateTime();
testTime = DateTime.ParseExact(test, "yyyy-MM-ddTHH:ssZ", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Console.WriteLine(testTime);
Console.ReadLine();
Results:
The format string you are using ("mm/DD/yyyy HH:ss") doesn't match your input in any way.
Have you looked at the DateTime.ParseExact documentation? You could try something like this:
testTime = DateTime.ParseExact(test, "yyyy-MM-ddTHH:ssZ",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal);
A couple of notes:
There is no point in setting testTime = new DateTime() if you are going to parse it on the next line. Just drop that line entirely and use var testTime = DateTime.ParseExact(...);
Are you sure that HH:ss is what you want? That seems like a very strange way to write a time. HH:mm or mm:ss would make more sense.
You should fix your expected pattern and take the time zone into account.
If your need a DateTime of DateTimeKind.Local:
var date = DateTime.ParseExact("2015-05-08T05:00Z", "yyyy-MM-dd'T'HH:mm'Z'",
CultureInfo.InvariantCulture);
If your need a DateTime of DateTimeKind.Utc:
var date = DateTime.ParseExact("2015-05-08T05:00Z", "yyyy-MM-dd'T'HH:mm'Z'",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal
| DateTimeStyles.AdjustToUniversal);
You are doing an exact parse, which means that the parse format string must match exactly with your date literal string. But your parse format string in ParseExact
uses / instead of - in the test literal string.
has a space instead of the T in the test literal string
does not match Z at the end of your test literal string.
Further it is not in yyyy-MM-dd order of your test literal string.
#Shar1er80' s solution is nice and frees you from having to specify a correct parse format string for ParseExact. I'd recommend going with that.
However, if you want to use ParseExact, you need to do this:
testTime = DateTime.ParseExact(test, "yyyy-MM-ddTHH:ssZ",
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
Note that I added a DateTimeStyle of AdjustToUniversal to ensure that your time is interpreted as UTC. The Z in the parse format string is just there to consume a Z. See https://stackoverflow.com/a/833143/49251 for more info on the issue of Z not actually being a part of the format string per se.

Date time format in C#

i have a string like "14-Nov-2014" , i want to convert this string to this 14.11.2014 format.
after converting i want to add 14 days to above date.
given date is not Datetime format.
Old date="14-Nov-2014"
new date=14.11.2014
is there any way to do in c#?
Assuming,
var myString = "14-Nov-2014";
First parse the string, most likely using DateTime.ParseExact. Assuming a few things about the format you have, you could do the following. Note you most likely should specify the proper culture for the third argument:
var dateTime = DateTime.ParseExact(myString, "dd-MMM-yyyy", null);
Then you can add 14 days to it easily:
var dateTime = dateTime.AddDays(14);
To get a new string in a different format just use ToString with a format string. For example:
var myNewString = dateTime.ToString("d.MM.yyyy");

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

Categories