Add time duration to date using addHours() in c# - 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);

Related

How to subtract DateTime field and Duration?

I have one field in database in this format: 2013-06-18 17:00:00.000
and second field Duration in this format: 3000 (this represents seconds, so it is 50 minutes)
I need to subtract those two fields and to set in another field result which will be: 2013-06-18 16:10:00.000
One addition is that they both can be retrieved from database in string format only. So they are both strings.
Thanks
First you need to Parse the datetime. Then subtract using AddSeconds:
var date = DateTime.Parse("2013-06-18 17:00:00.000");
var newDate = date.AddSeconds(int.Parse("-3000"));
You can use newDate.ToString() to get the date as a string.
You can find the documentation for DateTime here.
Update: Changed seconds to a string value. Which uses Parse to convert to an integer.
You can subtract to the datetime object. (if is a DateTime Type) if not, you should parse.
To handle errors, I would recommend to use DateTime.tryParse(value, out dateTime);
DateTime parsedDateFromBD;
if(DateTime.tryParse("2013-06-18 17:00:00.000", out parsedDateFromBD)
{
// do Stuff
}
else
{
// do something else
}
if you get it as a datetime from the db you can simply:
var calcDate1 = dateFromBD.addSeconds(3000); //to Add
var calcDate2 = dateFromBD.addSeconds(-3000); //to subtract
Cheers
Ricardo
In addition to the other answers here is how to parse the newDate to string that mach the required output
string date = "2013-06-18 17:00:00.000";
string duration = "-3000";
int durationSeconds = int.Parse(duration);
var newDate = DateTime.Parse(date).AddSeconds(durationSeconds).ToString("yyyy-MM-dd HH:mm:ss.fff");
The output is
//2013-06-18 16:10:00.000
Here you can find more about DateTime.ToString()

c# Sum to DateTime.Now.TimeOfDay; [duplicate]

I have a calendar and a textbox that contains a time of day. I want to create a datetime that is the combination of the two. I know I can do it by looking at the hours and mintues and then adding these to the calendar DateTime, but this seems rather messy.
Is there a better way?
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
If you are using two DateTime objects, one to store the date the other the time, you could do the following:
var date = new DateTime(2016,6,28);
var time = new DateTime(1,1,1,13,13,13);
var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);
An example of this can be found here
Depending on how you format (and validate!) the date entered in the textbox, you can do this:
TimeSpan time;
if (TimeSpan.TryParse(textboxTime.Text, out time))
{
// calendarDate is the DateTime value of the calendar control
calendarDate = calendarDate.Add(time);
}
else
{
// notify user about wrong date format
}
Note that TimeSpan.TryParse expects the string to be in the 'hh:mm' format (optional seconds).
Using https://github.com/FluentDateTime/FluentDateTime
DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);
DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.

Alternative Datetime.Now with only time (21:10)

I was wondering if there's a method or anything which will provide me the current systemtime without the date. I need to use this in a formula and if i want to use the DateTime.NowI have to String.Split this string before I can convert this to a Int.
example: It's 5pm
I want:
'17:00', '5:00', '1700', '500'
Not:
'17:00 PM 29/03/2013'
A DateTime holds the hour and minutes as properties.
var now = DateTime.Now;
var minutes = now.Minute;
var hours = now.Hour;
why cannot you simply format your date i.e.
string CurrentTime = DateTime.Now.ToString("hh:mm:ttt");
I guess what you are looking for is how to format a DateTime correctly.
Look here or here for how this is done.
You could use TimeOfDay. Basically it extracts the time part of a DateTime:
DateTime now = DateTime.Now;
TimeSpan time = now.TimeOfDay;
Do note that unlike the DateTime.Date property, DateTime.TimeOfDay returns a Timespan, not a DateTime.
for "1700" :
date.ToString('HHMM');
Use the DateTime.ToString method:
DateTime dt = DateTime.Now; // Suppose it is currently 5pm
dt.ToString("HH:mm"); // 17:00
dt.ToString("h:mm"); // 5:00
dt.ToString("HHmm"); // 1700
dt.ToString("hmm"); // 500

Join Date and Time to DateTime in C#

I am retrieving data from an iSeries where there is a separate date and time fields. I want to join them into a DateTime field in my C# project. I don't see a way to add just a time to a DateTime field. How would you suggest accomplishing this?
You can do this quite easily:
DateTime dateOnly;
DateTime timeOnly;
...
DateTime combined = dateOnly.Date.Add(timeOnly.TimeOfDay);
TimeOfDay returns a TimeSpan, which you then add to the date.
Edit (thanks to commenters below) - to be safe, use dateOnly.Date to ensure the date part only.
How are they being stored? Assuming that the date portion is being stored as a DateTime of midnight of the day in question and the time is a TimeSpan, you can just add them.
DateTime date = ...;
TimeSpan time = ...;
DateTime result = date + time;
You could easily construct a TimeSpan from your "time" field.
Once you have that, just do:
TimeSpan time = GetTimeFieldData();
dateField = dateField.Add(time);
Datetime date = new DateTime(Date1.Year, Date1.Month, Date1.Day, Time1.Hour, Time1.Minute, Time1.Second);
You can add a TimeSpan to a DateTime and write something like this.
// inside consuming function
ISeriesObject obj = getMyObject();
DateTime dt = getDate(obj) + getTime(obj);
private DateTime getDate(ISeriesObject obj)
{
//return a DateTime
}
private TimeSpan getTime(ISeriesObject obj)
{
//return a TimeSpan
}
My answer addresses joining two objects of DateOnly and TimeOnly in .NET 6:
DateOnly orderDate = ...
TimeOnly orderTime = ...
DateTime orderDateTime = orderDate.ToDateTime(orderTime);
This should do:
var output = date.Date + time.TimeOfDay;
or
var output = new DateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second);
suppose that both variable date and time are both of Type DateTime
Note that adding the time to the date is not your biggest problem here. As #Reed Copsey mentioned, you just create a DateTime from the date and then .Add the time.
However, you need to make sure that the iSeries date and time (a Unix time most probably) are in the same representation as the .Net representation. Thus, you most probably need to convert it by adding it to a Jan 1, 1970 DateTime as well.
Cant you simply format the date part and time part as separate strings, then join them together? Then you can parse the string back to a DateTime object

C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.

Categories

Resources