.NET Date Add Days - c#

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . Can some one suggest how to do that with this format and AddDays or AddHours ? Result need to return same format.

Try using DateTimeOffset.Parse. Then use AddDays or AddHours.
It is important to use DateTimeOffset instead of DateTime if you want to preserve the same timezone offset that you parsed.
var dateTimeOffset = DateTimeOffset.Parse("1999-05-31T13:20:00.000-05:00");
var newDateTimeOffset = dateTimeOffset.AddHours(1);
var newDateTimeString = newDateTimeOffset.ToString("O");
if you don't like the way "O" formats, you can use this:
var newDateTimeString = newDateTimeOffset.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK")
This will 100% match to your format.

Example:
txt_del.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
/* for date picking textbox*/
double d2 = double.Parse(txt_till.Text);
/*second textbox for number of days to add*/
DateTime tom = Calendar1.SelectedDate.AddDays(d2);
/*for adding number of days to selected date*/
txt_total.Text = tom.ToString("MM/dd/yy")

Use DateTime.Parse(...) to create a DateTime object. Then you can add days and/or hours, and then ToString() to get the new string.

That looks like datetimeoffset. Perhaps from sql server? You should be able to use the datetimeoffset structure and the parse method. Once you have a datetimeoffset type you can use addhours or related methods.

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.

How to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?
Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
var yesterday = DateTime.Now.AddDays(-1);
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance

Watin : Get Datetime and perform calculation

I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
You should use DateTime.Parse, DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact to parse from text to a DateTime.
If a failure to parse indicates a failure in the code somewhere (which is probably the case here, given that it's a test) I suspect DateTime.ParseExact is the most appropriate approach, providing the expected format, culture etc.
if what you want is to subtract 2 days from a date I would do it like this:
DateTime dt = DateTime.Parse(myDate)-TimeSpan.FromDays(2);
//its steps 1,2 & 3 in one easy to read line :)
This is of course if you are sure the string you have IS a valid date. If it might not be, then you should do what the Skeet recommends, which is using first a try parse, checking if the return value is true, and if it is, then do the rest, and if it is not, send an error message.
consider writing
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = new DateTime(dt.Year, dt.Month, dt.Day - 2);
browser.TextField(Find.ByName("myTextField")).TypeText(dtNew.ToShortDateString());
Try getting the value of the date as string
Convert it to datetime and use AddDays we can use negative or positive value
And insert it into textbox
string myDate = this.Elements.textfield.Value;
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = dt.AddDays(-3);
this.Elements.ChangeDateActive.TypeText(dtNew.ToShortDateString());
That's it thanks

Replace date in a DateTime with another date

How do you change the day part of a DateTime structure?
I have a DateTime with the value of 3/31/2009 8:00:00 AM and would like to change it to any other date but the time should be same. I don't need a solution to add day(s), I need to replace it with any arbitrary date.
How do I achieve this?
To construct a DateTime from two other DateTimes, one of which contains the date and one of which contains the time, you can use:
DateTime result = date.Date + time.TimeOfDay;
day = 1
month = 4
year = 2009
Date2 = new DateTime(day,month,year,Date1.Hours,Date1.Minute,Date1.Seconds)
s = s.AddDays(1)
You should use DateTime.AddDays method. Like this:
DateTime s2 = s.AddDays( 1 );

Categories

Resources