C# actual DateTime - 14 - c#

I want to have a the DateTime 14 days ago.
In C# you only can add days...
I tried this but it doesn't work:
DateTime daysToKeep = DateTime.Now;
daysToKeep.AddDays(-14);
thx.

You must assign the result:
DateTime daysToKeep = DateTime.Now;
daysToKeep = daysToKeep.AddDays(-14);
The AddDays() method does not modify the object itself.

DateTime daysToKeep = DateTime.Now.AddDays(-14);
You need to stress some concepts here.
DateTime Objects (Like String) are immutable, you can't change them. So their methods return new Objects and not change the object itself.
From MSDN:
When working with the DateTime structure, be aware that a DateTime
type is an immutable value. Therefore, methods such as AddDays
retrieve a new DateTime value instead of incrementing an existing
value. The following example illustrates how to increment a DateTime
type by a day using the statement dt = dt.AddDays(1).

Related

how to make -1(only for date ) from given date in c#

given date = 05-01-2021
Convert.ToDateTime(process.inorDate).AddDays(-1)
this is starting date 05-01-2021
the end date should be +12 months and -1. which means
Start = 05-01-2021
End = 04-30-2022
just doing -1 for date and updating year
Take a look at the constructors of DateTime, there is only 1 which takes a single argument, this one. And DateTime.AddDays() returns a DateTime struct. So you're basically doing:
DateTime converted = Convert.ToDateTime(process.inorDate);
DateTime oneDayBefore = converted.AddDays(-1);
new DateTime(ondeDayBefore);
See how it's unnecessary and even impossible to construct a new DateTime? Instead just use the oneDayBefore variable.

combine parts from 2 different datetime variables into a new datetime variable

I have 2 datetime objects that I need to combine.
This contains the correct date, but the time part is not needed.
DateTime? sessionDate = fl.EventDateTimeStart
This contains the correct time, but the date part needs to be the date value from the
sessionDate object above.
DateTime? sessionStartTime = g.GameStartTime.Value
I tried using some of the various DateTime toString() methods, but found out that
because they are part of a class, they need to remain DateTime? types
so I can't just convert them to a string.
So I came up with this really ugly method:
sessionStartTime = new DateTime(
fl.EventDateTimeStart.Value.Year,
fl.EventDateTimeStart.Value.Month,
fl.EventDateTimeStart.Value.Day,
g.GameStartTime.Value.Hour,
g.GameStartTime.Value.Minute,
g.GameStartTime.Value.Second)
Is there a more elegant way of to do this?
Thanks!
Sure.
var result = fl.Value.Date + g.Value.TimeOfDay;
DateTime.Date returns a DateTime with the time part set to midnight. DateTime.TimeOfDay gets a TimeSpan containing the fraction of the day that has elapsed since midnight.
Make sure that both of your DateTimes have the same Kind, otherwise the result might not be what you expect.

How to merge two nullable DateTime objects one contaning time other date I need into one object?

I've got two DateTime objects. The FetchTime contains time hh:mm:ss I am insterested in, FetchDate contains date: year, month, day.
Example:
Debug.WriteLine("Time " + FetchTime);
Debug.WriteLine("Date " + FetchDate);
displays for example:
Time 2014-09-10 23:04:00
Date 2014-09-15 00:00:00
and I would like to get DateTime object which looks like that:
2014-09-15 23:04:00
I would like to merge those two into one or modify one of them. I thought it would be easy but I can't see almost any methods for DateTime object. Is it achievable or first I must convert DateTime to another type then convert it back? Finally, I have to have DateTime object because it is going to be added to SQL database .
EDIT:
I refer to nullable DateTime: DateTime? FetchDate, DateTime? FetchTime.
Just use the DateTime constructor
var date = new DateTime(FetchDate.Year, FetchDate.Month, FetchDate.Day,
FetchTime.Hour, FetchTime.Minute, FetchTime.Second);
Update: It seems like you are using nullable DateTime. So you should get the underlying DateTime value using Value property.
var fetchDate = FetchDate.Value;
var fetchTime = FetchTime.Value;
var date = new DateTime(fetchDate.Year, fetchDate.Month, fetchDate.Day,
fetchTime.Hour, fetchTime.Minute, fetchTime.Second);
Whenever you use the ? suffix on a value type you will always need to call the .Value member before you can call any members on your type.
The ? suffix is actually a special symbol for the compiler to transform your type reference from T? to Nullable<T>. For additional details see the MSDN documentation for Nullable`1.
For your example you will want to use the following to merge the values together.
new DateTime(
FetchDate.Value.Year,
FetchDate.Value.Month,
FetchDate.Value.Day,
FetchTime.Value.Hour,
FetchTime.Value.Minutes,
FetchTime.Value.Seconds)
Make sure to check for null using == null or .HasValue if you are concerned about null values, otherwise you will encounter a System.InvalidOperationException.
For fun, here is another possible way:
DateTime date = new DateTime(2014, 9, 15);
DateTime datetime = new DateTime(2014, 9, 10, 23, 4, 0);
DateTime combined = date + datetime.TimeOfDay;

Getting only hour/minute of datetime

Using C#, I have a datetime object, but all I want is the hour and the minutes from it in a datetime object.
So for example:
if I have a DateTime object of July 1 2012 12:01:02 All I want is July 1 2012 12:01:00 in the datetime object (so, no seconds).
Try this:
String hourMinute = DateTime.Now.ToString("HH:mm");
Now you will get the time in hour:minute format.
Try this:
var src = DateTime.Now;
var hm = new DateTime(src.Year, src.Month, src.Day, src.Hour, src.Minute, 0);
Just use Hour and Minute properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.
If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.
That being said you can create a new DateTime object using only the properties you want as #romkyns has in his answer.

Constructing a DateTime one step at a time

I am trying to construct a DateTime in C# one step at a time, as in, the whole date not being in the constructor. I'm not understanding what is wrong though.
DateTime d = new DateTime((long)0);
d.AddYears(2000);
with that d.Years will still be equal to 1 though. Also, I must store the date as a long. So I can't just build the date with a huge constructor and I also can't have a persisting DateTime instance, so I dump it to a long and then restore it and I start with a value of 0. Am I suppose to start with a different value than zero?
what exactly is wrong?
A DateTime structure is immutable, meaning that its properties cannot change.
The AddYears method returns a new DateTime that you must use:
DateTime d = new DateTime((long)0);
d = d.AddYears(2000);
Probably off-topic, but if you need to persist your DateTime as a long then why not persist the value returned by its Ticks property.
You can then restore your DateTime instance by using the constructor that takes a ticks parameter:
// stage 1
DateTime dt = DateTime.MinValue.AddYears(2009);
PersistTicksToSomewhere(dt.Ticks);
// stage 2
long ticks = GetPersistedTicksFromSomewhere();
DateTime dt = new DateTime(ticks).AddMonths(8);
PersistTicksToSomewhere(dt.Ticks);
// stage 3
long ticks = GetPersistedTicksFromSomewhere();
DateTime dt = new DateTime(ticks).AddDays(20);
PersistTicksToSomewhere(dt.Ticks);
// etc etc
There are 12 different overloads for the DateTime constructor. There should be at least one you can adapt for your use.
This:
DateTime d = new DateTime(2000,0,0);
is better than:
DateTime d = new DateTime((long)0);
d = d.AddYears(2000);
Just construct as much of the date as you can up front and put in zeros for the other parameters.
DateTime is immutable so you must change it as so
DateTime d = new DateTime();
d d.AddYears(2000);
However this will instantiate a new DateTime 99.9% of the time this is fine but if it's nested in a loop that runs forever you're better off using one of the many DateTime constructors. Use the same rule of thumb as string and StringBuilder.

Categories