How to Convert string "07:35" (HH:MM) to TimeSpan - c#

I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.
Right now I have a "old fashion style":
string stringTime = "07:35";
string[] values = stringTime.Split(':');
TimeSpan ts = new TimeSpan(values[0], values[1], 0);

While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.

Use TimeSpan.Parse to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx

You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

Related

Convert 12 hour time to Timespan C#

Using ASP.NET Forms, I'm encountering a problem with converting a 12 hour time into a timespan. Below I'm combining DateTime with TimeSpan as the user chooses a date and then a time. The fields are controlled by javascript.
DateTime DateResult = DateTime.TryParse(txtDate.Text, out DateResult) ? DateResult : DateTime.Today;
TimeSpan TimeResult = TimeSpan.TryParseExact(txtTime.Text, "h:mm tt", CultureInfo.InvariantCulture, out TimeResult) ? TimeResult : new TimeSpan();
DateResult = DateResult.Add(TimeResult)
So parsing the date works fine, but Timespan doesn't. One example:
Date Entered: 08/03/2018
Time Entered: 3:00 AM
Values are gettined passed okay but time fails so DateResult becomes "08/03/2018 00:00" but not "08/03/2018 03:00". I have also tried using the method TimeSpan.TryParse but no luck with that one.
I've also made sure that the format is correct by manually entering the time in the database behind the scenes. The gridview has a column that shows the full date in this format "dd/MM/yyyy h:mm tt", and works.
Anyone please share some light? Ideally, I would like to avoid any third party plug-ins.
Parse them together
Simplest thing is to just concatenate the strings before parsing as a single DateTime, e.g.
var dateEntered = #"08/03/2018";
var timeEntered = #"3:00 am";
DateTime result;
var completeDateString = dateEntered + " " + timeEntered;
var ok = DateTime.TryParse(completeDateString, out result);
if (!ok) result = DateTime.Today;
Console.WriteLine(result);
Output:
8/3/2018 3:00:00 AM
Ta da
If you have to parse them separately
If you'd like to work with the fields separately, you still can (I guess you'd have to do this if you want the time format to be exact but the date portion to be flexible, as it is in your example). But TimeSpan.TryParseExact is really different from DateTime.Parse. The format codes are different; it doesn't support the ":" character (except as a literal with an escape, e.g. "\:"), for example, or the "tt" formatting specifier. I'm guessing the concept of am/pm has to do with an absolute point in time, not a relative time offset, so isn't provided for. But you can still parse the textbox as a DateTime and use its time portion.
You can probably shorten this a bit but this example gives you everything you need:
static public DateTime ParseDateTime(string input)
{
DateTime output;
var ok = DateTime.TryParse(input, out output);
if (ok) return output;
return DateTime.Today;
}
static public TimeSpan ParseTime(string input)
{
DateTime output;
var ok = DateTime.TryParseExact(input, #"h:mm tt", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out output);
return output.Subtract(output.Date);
}
public static void Main()
{
var dateEntered = #"08/03/2018";
var timeEntered = #"3:00 am";
DateTime dateResult = ParseDateTime(dateEntered);
TimeSpan timeResult = ParseTime(timeEntered);
DateTime finalResult = dateResult.Add(timeResult);
Console.WriteLine(finalResult);
}
Output:
8/3/2018 3:00:00 AM
Code on DotNetFiddle
See ParseExact or https://msdn.microsoft.com/en-us/library/system.timespan.tryparseexact(v=vs.110).aspx for TryParseExact should work for both DateTime as well as TimeSpan inter alia
Fyi it's called the meridian and see also AM/PM to TimeSpan

Add time duration to date using addHours() in c#

I want to add time duration to my datetime variable. I am reading the duration from a csv file. The format of duration is 0:29:40 or 1:29:40. When i add this to datetime variable it gives exception of incorrect format. How can I add the duration using this format. Previously I had duration as a simple integer like "6" or "7" but now the format is this "0:29:40" I don't know how to change my code to accommodate this format.
Previously i was doing this
double hours = Convert.ToDouble(row.Cells[2].Value.ToString());
DateTime newdate = finaldate.AddHours(hours);
row.Cells[2].Value.ToString() reads the value from csv
Any help is appreciated, Thanks
You don't need to parse to a double. Parse to a TimeSpan. Something like:
var source = "0:29:40";
var ts = TimeSpan.Parse(source);
Now ts is your time span. And the nice thing with TimeSpan is you can just add it to a DateTime:
DateTime newdate = finaldate + ts;
You are going to need to use the TimeSpan.Parse() or TimeSpan.ParseExact() method to properly parse your string and then simply add that TimeSpan result to your existing date:
var time = TimeSpan.Parse(row.Cells[2].Value.ToString());
DateTime newDate = finalDate.Add(time);
If you need to explicitly specify what each of the values of your time represent, then the TimeSpan.ParseExact() method will allow you to provide a formatting string to specify this:
// This will assume that 1:29:40 is hours, minutes, and seconds
var time = TimeSpan.ParseExact(row.Cells[2].Value.ToString(), #"h\:m\:s", null);

How to compare 12-hour/24-hour formatted time strings in C#?

How do I compare which time string is greater; be it in 24-hour or 12-hour format?
For example, "9:42:54" vs "19:25:31" or "9:42:54 AM" vs "7:25:31 PM".
To be able to compare strings in time format, you need to convert them to TimeSpan or DateTime objects, but the former seems to be more relevant:
TimeSpan time1 = TimeSpan.Parse("9:42:54");
TimeSpan time2 = TimeSpan.Parse("19:25:31");
or
TimeSpan time1 = DateTime.Parse("9:42:54").TimeOfDay;
TimeSpan time2 = DateTime.Parse("19:25:31").TimeOfDay;
However, using TimeSpan.Parse for 12-hour time string formats will throw a System.FormatException. Use DateTime.Parse instead and take only the time part of the created DateTime object:
TimeSpan time1 = DateTime.Parse("9:42:54 AM").TimeOfDay;
TimeSpan time2 = DateTime.Parse("7:42:54 PM").TimeOfDay;
As a benefit, converting to TimeSpan will also give you a chance to apply TimeSpan operators like regular comparison, subtraction, addition, etc.:
if (time1 > time2)
{
// time1 is greater
}
else if (time1 < time2)
{
// time2 is greater
}
else
{
// They are equal
}
You can also use TimeSpan.ParseExact if you need to the specify the time format of your string explicitly.

Unable to convert a string to DateTime?

Inside a function, I need to find the difference between 2 dates in seconds. If the difference is more than 30 seconds i return False otherwise it returns True , first one I read it from database and Second one is the current DateTime.Now
Here is the snippest of code I'm using that does the work while dr.GetValue(0).ToString() holds the current value in the database :
if (dr.Read())
{
DateTime nowDate = Convert.ToDateTime(DateTime.Now.ToString("M/dd/yyyy H:mm:ss tt"));
DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
TimeSpan diff = nowDate - then;
int timeDifference = diff.Seconds;
if (timeDifference > 30)
{
myConn.Dispose();
return false;
}
else {
myConn.Dispose();
return true;
}
}
When i execute the code above i get a message error : string was not recognized as valid DateTime
And here is the line that is causing the error :
DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
The time is stored in the database in this format : 2013-02-18 14:06:37
But when I execute the following line (for debugging purposes) :
MessageBox.Show(dr.GetValue(0).ToString());
I see a message box that shows the date in this format : 2/18/2013 2:06:37 PM
How to find the difference in seconds between the current time and the time stored in dr.GetValue(0).ToString()
Any help would be highly appreciated
You want h, not H. h is the hour in 12-hour format, H is the hour in 24-hour format. Since your example hour is 2 PM (not 14 PM) it's the 12-hour format you want.
Also:
You're converting your now-time to a string and back - don't bother!
You're counting Seconds not TotalSeconds - this is incorrect because e.g. a 60-second period gives a Seconds value of 0.
DateTime nowDate = DateTime.Now;
DateTime then = DateTime.ParseExact(
dr.GetValue(0).ToString(), "M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
TimeSpan diff = nowDate - then;
double secondsDifference = diff.TotalSeconds;
You should even be able to do something along the lines of
DateTime then = dr.GetDateTime(0);
and avoid the string-parsing altogether, but the H/h difference is the reason you get the specific exception you asked about.
if, as it looks like, your date is a datetime in the database, you can probably simplify the two lines to this:
DateTime nowDate = DateTime.Now;
DateTime then = (DateTime)dr.GetValue(0);
(although I'm making a lot of assumptions here)
Your code really should be very simple:
if (dr.Read())
{
DateTime then = dr.GetDateTime(0);
TimeSpan diff = DateTime.Now - then;
int timeDifference = diff.TotalSeconds;
}
One thing to note - you really shouldn't be calling myConn.Dispose(); in your if/else. Wrap your connection and readers in a using statement.
I think your server has Application server has some other date format set. What you can try is this:
Convert.ToDate(value,System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormate);
Hope this will solve the error.Haven't tested it so hope for best

date difference between two dates

I want to calculate the date difference between form date and two date..Am using timespan to calculate the difference between two date if date difference is positive means it enter another process falls means it return error message.
My partial code is here..
TimeSpan span = Convert.ToDateTime(txtenddate.Text).Subtract(Convert.ToDateTime(txtstartdate.Text));
int formatted = span.Days;
if (formatted < 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Invalid date difference ');</script>", false);
}
In the above code input is end date : 30-01-2004 start date : 01-02-2002
but it returns error message : String was not recognized as a valid DateTime.
please give me a solution to solve this with out changing date format...
You should be using ParseExact to get the relevant DateTime.
TimeSpan ts = DateTime.ParseExact("30-01-2004", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture)
- DateTime.ParseExact("01-02-2002", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
While using Convert.ToDateTime it invokes DateTime.Parse which will try the conversion corresponding to the your current culture setting which as in this case doesn't support the format of DateTime you have, so you should rely on the ParseExact whereby you know the format in which the string is expected and achieve in fetching your result.
You need to specify the culture for the conversion. By default, it should be using the default date format for your PC but this doesn't always work.
You should take a look at this about specifying a format provider for the Convert.ToDateTime method http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx
and this about the DateTimeFormatInfo object you will need to create to handle the culture: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
You must use CultureInfo maybe the default CultureInfo different from "en-GB";
var cult = new System.Globalization.CultureInfo("en-GB");
TimeSpan span = Convert.ToDateTime("30-01-2004", cult).Subtract(Convert.ToDateTime("01-02-2002", cult));
Your dateformat should be like this. StartDate=1/2/2002 and EndDate=3/1/2004
for days difference
public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}
Date difference between days with time
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);

Categories

Resources