I am looking for a elegant solution (if it exists) to achieve what I described in the title.
I saw an elegant solution for "changing the time in a DateTime object" and it is as follows:
DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;
If there such a solution for changing the date in a DateTime object?
DateTime struct is designed to be immutable, so you can't change it. You can get a new one based on values from the old one, which is exactly what your solution does.
You can make it a bit more clear by using DateTime constructor which takes all date and time values: year, month, day, hour, minute and seconds.
s = new DateTime(s.Year, s.Month, s.Day, 10, 30, 0);
s = new DateTime(2014, 10, 2, s.Hour, s.Minute, s.Second);
or you can use TimeOfDay property:
s = new DateTime(2014, 10, 2) + s.TimeOfDay;
Assuming that you are going to pass a new DateTime object to update your existing object, a function like this can work.
DateTime UpdateDate(DateTime existingDate, DateTime newDate)
{
return newDate.Date + existingDate.TimeOfDay;
}
myDatetime = new DateTime(year, month, day);
You can use the DateTime constructors, so you can preserve the original time.
See this example:
var firstDate = new DateTime(2015, 01, 01, 15, 0, 0);
var newDate = DateTime.Now;
// New date, original time.
firstDate = new DateTime(newDate.Year, newDate.Month, newDate.Day, firstDate.Hour, firstDate.Minute, firstDate.Second, firstDate.Millisecond);
Try this:
DateTime s = ...;
s = new DateTime(year, month, day) + s.TimeOfDay;
That preserves the time in the original DateTime.
Try this:
DateTime now = DateTime.Now;
DateTime dateOnly = now.Date;
TimeSpan time = now.TimeOfDay;
dateOnly = DateTime.Parse("5/15/15"); // or whatever date you choose
DateTime newDateTime = dateOnly + time;
Related
I am trying to simply subtract two dates. Probably this is a messy way of doing it. It says it cannot convert to double even though.
DateTime daysPlus14days = _dal.getOptinDate(new Guid(_myuser.id.ToString())).AddDays(14);
DateTime currentDate = DateTime.Now;
DateTime timeLeft = (daysPlus14days - currentDate).TotalDays
This just basically goes to db and gets me the date they created there account. Its just to work out how many days left they have 14 days to click a button other wise it will vanish.
public DateTime getOptinDate(Guid id)
{
var q = _dal.portalEntities.tblPortalUsers.Where(a => a.id == id).FirstOrDefault();
return (DateTime)q.optinDateStart;
}
just change this line:
double timeLeft = (daysPlus14days - currentDate).TotalDays;
TotalDays returns double and not DateTime
Refer this link https://msdn.microsoft.com/en-us/library/system.timespan.totaldays(v=vs.110).aspx,
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.TimeSpan diff1 = date2.Subtract(date1);
double totaldays = diff1.TotalDays;
how can I calculate if a date (in DateTime format) is 6 month later or not from my BirthDate (in DateTime format)?
Use DateTime AddMonth method
https://msdn.microsoft.com/ru-ru/library/system.datetime.addmonths(v=vs.110).aspx
var dat = new DateTime(2015, 12, 31);
var dat2 = new DateTime(2015, 12, 31);
if (dat.AddMonths(6) < dat2) { ... }
You should use DateTime.AddMonths :
DateTime dt;
DateTime birthDate;
if (dt <= birthDate.AddMonths(6))
{
}
enter your birth date, calculate your next birthday and compare the dates,
var born = new DateTime(1900, 02, 01);
var checkdate = DateTime.Now;
var nextBirthday = new DateTime(DateTime.Now.Year, born.Month, born.Day);
if (nextBirthday < DateTime.Now)
{
nextBirthday = new DateTime(DateTime.Now.Year + 1, born.Month, born.Day);
}
if (checkdate.AddMonths(6) < nextBirthday)
{
Console.WriteLine("date is 6 months later then birthday");
}
else
{
Console.WriteLine("wait for it");
}
DateTime birthDate=new DateTime(year,month,day);
DateTime dateToCompare = new DateTime(year, month, day);
if(dateToCompare >= birthdate.AddMonths(6))
{
//DoSomething
}
You could calculte the difference between dates using Subtract method and calculate how many months you have between these dates, for sample:
DateTime birthDay = /* some date */;
DateTime someDate = /* some date */;
var months = someDate.Subtract(birthDay).Days / (365.25 / 12);
This answer provides a good helper for Dates:
https://stackoverflow.com/a/33287670/316799
I would like to set principal.AccountExpirationDate with a dateTimePicker1
if i do this - its work:
principal.AccountExpirationDate = new DateTime(2015, 12, 12);
but when i try to use the dateTimePicker1 its not work - this is my code:
string enddate = dateTimePicker1.Value.ToString("yyyy, MM, dd");
int val = Convert.ToInt32(enddate);
principal.AccountExpirationDate = new DateTime(val);
Im getting error.
how can i covert the dateTimePicker1 to a value that i can set in the principal.AccountExpirationDate?
You cannot convert DateTime or DateTime formated string to integer but you can take dateTime.Day, dateTime.Month or dateTime.Year as an integer separately.
int val = dateTimePicker1.Value.Day;
int month = dateTimePicker1.Value.Month;
int year = dateTimePicker1.Value.Year;
principal.AccountExpirationDate = new DateTime(year, month, val);
But principal.AccountExpirationDate = dateTimePicker1.Value is better one because dateTimePicker1.Value returns DateTime
How to get the start date and end date of month in different variable. I have tried this and I get the start date but unable to find the end date
DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd HH:mm:ss.fff");
DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(30).ToString("yyyy-MM-dd HH:mm:ss.fff");
This logic fails when month end date is 31 and 28 or 29. Your Help are surely appretiated.
You can calculate endDate like this:
DateTime endDate = startDate.AddMonths(1).AddDays(-1);
To get First Date
public DateTime FirstDayOfMonth(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
To get Last Date
public DateTime LastDayOfMonth(DateTime dateTime)
{
DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}
DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)
.AddMonths(1).AddDays(-1);
You already had the start date :
DateTime monthStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
There's a method to get the number of days in a month (and Looking at the IL code, it seems that this way is more efficient than the other answers, though unless you're going to do it a billion time, I doubt there will be any difference) :
int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
DateTime monthEndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, daysInMonth);
For first date:
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);
For last date:
DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));
I just want to add 1 day to a DateTime. So I wrote:
DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);
TimeSpan t = new TimeSpan(1, 0, 0, 0);
date.Add(t);
Console.WriteLine("A day after the day: " + date.ToString());
I thought the result would be: 2010 04 30- 10:25:00 but I'm still getting the initial date.
What's wrong?
DateTime values are immutable. The Add method returns a new DateTime value with the TimeSpan added.
This works:
Console.WriteLine("A day after the day: " + date.Add(t).ToString());
You need to change a line:
date = date.Add(t);
dtb is right about DateTime being immutable. Think of it this way: a DateTime is a value type, which puts it in the same category as int or double. Instances of these structures cannot be modified; they can only be evaluated and copied.
Consider this code:
int i = 4;
i + 2; // does not compile, but what if it did?
// would i become 6? clearly not --
// i + 2 expresses a NEW value, which can
// be copied somewhere
i = i + 2; // there we go -- that's better
This is analogous to:
DateTime d = DateTime.Now;
TimeSpan t = TimeSpan.FromDays(1.0);
d.Add(t); // compiles (because AddDays is a function),
// but is really the same as i + 2 above
d = d.Add(t); // that's better
By the way, one thing that might help make this clearer is realizing that the above line, d = d.Add(t), is the same as d = d + t. And you wouldn't write d + t on its own line, just like you wouldn't write i + 2 on its own line.
A DateTime is immutable, but the Add and Subtract functions return new DateTimes for you to use.
DateTime tomorrow = DateTime.Now.AddDays(1);
What is wrong with just doing date = date.AddDays(1)?
The result of date.Add(t) is what you're after:
DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);
TimeSpan t = new TimeSpan(1, 0, 0, 0);
// The change is here, setting date to be the *new* date produced by calling Add
date = date.Add(t);
Console.WriteLine("A day after the day: " + date.ToString());
date.Add(t);
returns a modified DateTime and does not change the original instance on which you call the Add method on.
DateTime wont work if DateTime obj datatype is "DateTime?" which takes accepts null values, in such case DateTime? dt = DateTime.Now;
DateTime dateObj = new DateTime();
dateObj = Convert.ToDateTime(dt.ToString());
var Month3 = dateObj.AddMonths(3);`