Add hours and minutes from string into datetime - c#

string date = "17:25";
if(date.Lenght == 5){
myobj.StartTime = DateTime.ParseExact(date, "HH:mm", CultureInfo.InvariantCulture);
// add only hh and minutes and preserve day and year
}
else if(date.Lenght > 5){
myobj.StartTime = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
}
myobj.StartTime is obviously of DateTime datatype.
I know I could break this string on : and use first part as hours and then convert that to double and then use AddHours, and I should repeat that for minutes also but I'm wonder is there convenient way to do this?

You can use TimeSpan.ParseExact:
myobj.StartTime = myobj.StartTime.Add(TimeSpan.ParseExact(date, "hh\\:mm", CultureInfo.InvariantCulture));
In hh\\:mm hh are hours (you cannot use HH here, not supported by this concrete method), mm are minutes, and \\: is escaped : character. One slash is to escape slash itself in C# literal string (otherwise you can do this: #"hh\:mm"), and you need to escape : with slash in format string, because otherwise TimeSpan.ParseExact will treat it as custom format specifier (like h), but there is no such format specifier and it will throw invalid format exception.
Note that if you also allow single-digit hours and minutes (like this: "1:2" or "1:25") - then you have to use another format:
TimeSpan.ParseExact(date, #"h\:m", CultureInfo.InvariantCulture);
This format will handle both single-digit and two-digit hours and minutes.
Also note that if you have more than 24 hours in your string (like "25:11") - this method will not work and you will have to fallback to split (as far as I know).

Related

string not recognized as a valid datetime in c# ERROR

Even after using DateTime.ParseExact I am getting error as
string not recognized as a valid datetime in c#
Below is my code
string strIDODDate = DateTime.ParseExact(ObjIp.ID_ODchangeDate, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy");
Here is full set of code
string strRFCsDate = DateTime.Now.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture);
//string strRFCsDate1 = DateTime.ParseExact("25-09-2019 00:00:00.000", "dd-MM-yyyy hh:mm:ss.fff", CultureInfo.InvariantCulture)
// .ToString("dd-MM-yyyy");
if (string.IsNullOrEmpty(ObjIp.ID_ODchangeDate))
{
Tobj.ID_ODchangeDate = strRFCsDate;
}
else
{
//Tobj.ID_ODchangeDate = Convert.ToString(ObjIp.ID_ODchangeDate);
string strIDODDate = DateTime.ParseExact(ObjIp.ID_ODchangeDate, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy");
Tobj.ID_ODchangeDate = strIDODDate;
}
update
After debugging, I found out that the format which was coming was with exception was below
10/28/2021 5:34:35 AM : 10/7/2019 12:00:00 AM 10/28/2021 5:34:35 AM : Error : Dumping into Table Process : String was not recognized as a valid DateTime. at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
Based on your comments and update:
ObjIp.ID_ODchangeDate was coming in 10/7/2019 12:00:00 AM
You are telling ParseExact a your format is "dd-MM-yyyy hh:mm:ss tt" this means a few things:
Your day will ALWAYS have 2 digits, meaning a leading 0 (you have 10)
Your month will ALWAYS have 2 digits, meaning a leading 0 (you have 7)
Your Year will have 4 digits (you have 2019)
Your separator will be '-' (you have /)
You will be using the 12 hour clock, including seconds (you have 12:00:00 AM)
The example you gave is not true for 2 and 4 of my list. I expect it won't be true for 1 for the first 9 days of any month, because of this you need to specify a format that doesn't include leading 0s and uses the correct date separators. The format you want is "d/M/yyyy hh:mm:ss tt" this format tells the parser:
The day will have 2 digits if it needs them, no guaranteed leading 0
The month will have 2 digits if it needs them, no guaranteed leading 0
The year will have 4 digits
The separator will be '/'
The time will be using the 12 hour clock, including seconds
That means the code will look like this. I pulled the formats out into variables for readability, and turned object.property into a variable to make it run simply in fiddle.
string ObjIp_ID_ODchangeDate = "10/7/2019 12:00:00 AM";
string dtFormatIn = "d/M/yyyy hh:mm:ss tt";
string dFormatOut = "dd-MM-yyyy";
string strIDODDate = DateTime.ParseExact(ObjIp_ID_ODchangeDate, dtFormatIn, CultureInfo.InvariantCulture).ToString(dFormatOut);
Console.WriteLine(strIDODDate);
As you can see, this works for your case.
Unclear from your question, so I'm assuming your incoming date time string is something like 25-09-19 00:00:00.000
var inDateTime = "25-09-19 00:00:00.000";
string parsedDateTime = DateTime.ParseExact(inDateTime, "dd-MM-yy hh:mm:ss.fff", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy");
Console.WriteLine(parsedDateTime);
Output
25-09-2019
UPDATE:
Please review: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
These are the date and time format strings for parsing date times.
It's still unclear if your value is October 7 or July 10... Assuming July 10:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
var inDateTime = "10/7/2019 12:00:00 AM";
string parsedDateTime = DateTime.ParseExact(inDateTime, "dd/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy");
Console.WriteLine(parsedDateTime);
}
}
Output
10-07-2019
See:
https://dotnetfiddle.net/2YMb82

Convert string into mm/dd/yyyy format

I have following strings in different formats:
16/05/2014
21-Jun-2014
2014-05-16
16-05-2014
5/19/2014
14 May 2014
I need to convert all the above strings into mm/dd/yyyy format in c#.
I have tried used DateTime.ParseExact as DateTime dt = DateTime.ParseExact("16-05-2014", "mm/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) in C# but i am getting the exception as "String was not recognized as a valid DateTime".
I have also tried to use to Convert.ToDateTime() but it is also not working.
Is there any method or function that we can write/available in C# that would convert the above string formats into a single date format i.e into "mm/dd/yyyy" format ??
Any help on this would be greatly appreciated.
It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.
You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:
string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.
Your main problem is that your format string is wrong. A small m is for minute, a big M is for month.
Try to pass all your formats in an array. For example like this
DateTime.ParseExact("16-05-2014",
new[] {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"},
CultureInfo.InvariantCulture, DateTimeStyles.None);
With this you can parse all your formats at once.
For more information about the format settings, see the official docs.
Few things:
Your input date 16/05/2014 doesn't match your format Month/Day/Year - how can there be a 16th month?
Secondly, you're using mm which represents Minutes, not Months. You should use MM.
Finally, your sample string 16-05-2014 doesn't match the format provided, you've used hyphens - instead of forward slashes /
Supply a collection of different formats matching your input:
string[] formats = new [] { "MM/dd/yyyy", "dd-MMM-yyyy",
"yyyy-MM-dd", "dd-MM-yyyy", "dd MMM yyyy" };
DateTime dt = DateTime.ParseExact("05-16-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
You might find the following method useful to accept whatever date format you want and convert it to DateTime:
public DateTime? DTNullable(string DateTimestring, string CurrDateTimeFormat)
{
if (string.IsNullOrEmpty(DateTimestring)) return null;
else
{
DateTime datetimeNotNull;
DateTime.TryParseExact(DateTimestring, CurrDateTimeFormat, null, System.Globalization.DateTimeStyles.None, out datetimeNotNull);
return datetimeNotNull;
}
}
Pass in your desired string to be converted to DateTime along with it's current date time format and this would return you a nullable DateTime. If you're certain that whatever string you're passing in won't be null then you can remove that bit. The reason for it being there is that you can't convert a null to DateTime. In my case I couldn't be certain if it would be or not so I needed the ability to capture nulls as well.
You can use it like this:
DateTime? MyDateTime = DTNullable(MyStartDate, "dd/MM/yyyy");
If you wanted you could alter the method to accept an array of strings and simply iterate through each and return them all in a list if they were of the same format.
As others have pointed out, months are MM not mm (minutes).
On a DateTime object you can call .ToString("MM/dd/yyyy"). Given the strings you have, you can first create new DateTime objects for each string and then call .ToString("MM/dd/yyyy"). For example:
var dateAsMmDdYyyy = DateTime.Now.ToString("MM/dd/yyyy");

How to escape the GMT in "yyyyMMddThhmmss.000GMT"?

I am using JsonConverter attribute to set my datetime format but for the string
"yyyyMMddThhmmss.000GMT" I get dates like "19900321T20000.000G3T" because of the latter M. How do I escape these characters in my format string?
You can use:
"yyyyMMdd'T'HHmmss'.000GMT'"
I changed hh to HH since most (sane) people use a 24-hour count.
On the documentation Custom Date and Time Format Strings it is shown that aopstrophe characters like in 'string' can be used for literal string delimiters. Now I also put the T inside this delimiter, just for clarity, even if one capital T has no other meaning in a DateTime format string.
Use single quote to escape like:
"yyyyMMddThhmmss'.000GMT'"
Like:
string str = "19900321T20000.000GMT";
DateTime dt = DateTime.ParseExact(str,"yyyyMMddTHHmms'.000GMT'", CultureInfo.InvariantCulture);
Change hh to HH for 24 hours, also it appears your seconds are single digit values, so use a single s.
(I assume in your question original string you have GMT, not G3T)
You have 2 options to use your ...GMT part as string literal delimiter in custom date and format string:
".000GMT"
'.000GMT'
But I suggest to use single quotes because if you use double quotes, you need to escape your quotes with \ (because of escape sequence) or you can use verbatim string literal.
Do the same thing with T middle in your string as well.
Also use HH specifier which is for 24-hour clock and use s speficier instead of ss because you have 5 digit after your T that's why it doesn't accept HHmmss format.
The reason of you get G3T it is because M is has meaning of month of custom string format and that's why your GMT parsed as G3T.
string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd'T'HHmms'.000G3T'",
CultureInfo.InvariantCulture);
With double quotes;
string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd\"T\"HHmms\".000G3T\"",
CultureInfo.InvariantCulture);

Date and time conversion in C# - DateTime.ParseExact() not working as expected

I have date/time format, for example:
"1-Mar-13 92230"
According to this document and this link the format is as follows:
"d-MMM-yy Hmmss", because:
Day is single digit, 1-30
Month is 3 letter abbreviation, Jan/Mar etc.
Year is 2 digits, eg 12/13
Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09)
Minute is standard (eg 01, 52)
Second is standard (eg 30, 02)
I'm trying to run the following code in my program, but I keep getting an error of "String was not recognized as a valid DateTime."
string input = "1-Mar-13 92330";
var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss",
System.Globalization.CultureInfo.CurrentCulture);
Please help, I'm not too familiar with DateTime conversions, but I can't see where I've gone wrong here. Thanks!
UPDATE: Is this because time cannot be parsed without colons in between? (eg 1-Mar-13 9:22:30 gets parsed, but i have an external data source that would be impossible to rewrite from Hmmss to H:mm:ss)
You could fix your date:
var parts = "1-Mar-13 92230".Split(' ');
if (parts[1].Length == 5)
{
parts[1] = "0" + parts[1];
}
var newDate = parts[0] + " " + parts[1];
var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss", System.Globalization.CultureInfo.CurrentCulture);
From msdn:
If format is a custom format pattern that does not include date or
time separators (such as "yyyyMMdd HHmm"), use the invariant culture
for the provider parameter and the widest form of each custom format
specifier. For example, if you want to specify hours in the format
pattern, specify the wider form, "HH", instead of the narrower form,
"H".
so you can try:
string input = "1-Mar-13 92330";
var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss",
System.Globalization.CultureInfo.InvariantCulture);
Your input string has to be of following format
string input = "1-Mar-13 092330";
If you go back to your link, it says
H 24-hour clock hour (e.g. 19)
Now H is 24 hours, it should be represented with leading 0. If not imagine how would you handle the case of hours greater than 9 i.e which are in double digit.
If not your hour and Minute and Seconds has to be separated.
string input = "1-Mar-13 9 2330";
var date = DateTime.ParseExact(input, "d-MMM-yy H mmss",
System.Globalization.CultureInfo.InvariantCulture);
Your hour min and seconds need to be separated, as they are not getting distinguished.
string input = "1-Mar-13 9 23 30";
var date = DateTime.ParseExact(input, "d-MMM-yy H mm ss", System.Globalization.CultureInfo.CurrentCulture);

How I can get the difference by time string and Datetime now?

i want to calculate a checktime to the time now and get the hours.
I have a string "time" for example...
Jun 06 2013 07:23:06
and with DateTime.Now I get the Time now. The Problem is now that i can't calculate the difference :(
I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.
You can use the Parse method of the DateTIme class to parse a string as a date and the subtract that from now.
TimeSpan diff = DateTime.Now - DateTime.Parse(dateString);
var hours = diff.Hours
The above exsmple of course requires the date to be in a specific format. You can if needed use DateTIme.ParseExact and specify a specific format yourself
You need to first convert your string to DateTime. here you have custom format so you can use DateTime.ParseExact or DateTime.TryParseExact method as below
DateTime dt;
if (DateTime.TryParseExact("Jun 06 2013 07:23:06", "MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// get difference
var inDays = (DateTime.Now - dt).Days;
}
You can use TimeSpan.Hours property like;
Gets the hours component of the time interval represented by the
current TimeSpan structure.
string dateString = "Jun 06 2013 07:23:06";
var differenceHours = (DateTime.Now - DateTime.Parse(dateString)).Hours;
Console.WriteLine(differenceHours);
Here a DEMO.
If you want to convert your custom formatted string to DateTime, you can use DateTime.ParseExact which need exact format matching between string and datetime.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
u may try it
DataTime diff = DateTime.Now - Convert.ToDataTime(dateString);
var hours = diff.Hours

Categories

Resources