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.
Related
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.
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.
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).
I have a datetime field like
{01/01/0001 00:01:02}
Millisecond = 30 and the Ticks for the above datetime field is
6203000000
The ticks save in the database as an int value which is 62030. I need to reproduce the above date time using the value in the database (62030). So I tried the following.
var data = 62030;
winTime = new DateTime().AddTicks(Convert.ToInt64(data.ToString().PadRight(10, '0')));
var b = winTime.Ticks;
var b = 6203000000. But it returns minute as 10 instead 01, second as 20 instead of 02 and Millisecond as 300 instead of 030.
Can anyone see what I'm doing wrong?
It seems to me that your "ticks 62030" is actually "milliseconds 62030" in which case it's very simple - you just need to multiply by "the number of ticks per millisecond" which is 10,000. You don't need to use DateTime for this at all:
// Note that if you want any significant length of time, you'd expect to get
// the data as a long, not an int
int data = 62030; // Milliseconds
long ticks = data * 10000L;
... and you certainly don't need string conversions. Converting to a string, padding, and then converting back again is a very tortuous and error-prone way of performing multiplication.
Or if you do need a DateTime:
int data = 62030; // Milliseconds
long dateTime = new DateTime(data * 10000L);
I strongly suspect that any DateTime value that early should actually be treated as a TimeSpan though - what's this really meant to represent? If so, it's even easier:
TimeSpan ts = TimeSpan.FromMilliseconds(data);
Date and time concepts are very easy to mix up, and you end up with some very subtle bugs. Personally I'd recommend using my Noda Time project which separates them more than .NET does, but even if you don't use the library it's worth looking at the list of concepts so you can think about them appropriately within .NET too.
Why not just use the DateTime constructor that accepts an Int64 representing ticks, such that:
var dateTimeFromTicks = new DateTime(ticks);
static void Main(string[] args)
{
/* read datetime now */
DateTime dt = new DateTime();
dt = DateTime.Now;
/* datetime convert to tick */
long TickeringTick = dt.Ticks;
Console.WriteLine("Date time now -> " + dt.ToString("yyyy.MM.dd HH:mm:ss.fffffff"));
Console.WriteLine("Converted to Ticks = " + TickeringTick.ToString());
/* convert tick to datetime */
long myTicks = TickeringTick;
DateTime dt2 = new DateTime(myTicks);
Console.WriteLine("Date from ticks :" + dt.ToString("yyyy.MM.dd HH:mm:ss.fffffff"));
Console.ReadLine();
}
I want to add seconds (00:00:02) or minutes (00:00:20) on datetime value (may be stored string type) but how? Examples:
13:30+02:02:02= 15:32:02 ,
13:30+00:00:01= 13:30:01 ,
13:30+00:01:00=13:31:00 or 13:30 (not important)
Can you help me? I need your cool algorithm :) Thanks again...
myDateTimeVariable.Add(new TimeSpan(2,2,2));
If you choose to use the TimeSpan, be aware about the Days part:
TimeSpan t1 = TimeSpan.Parse("23:30");
TimeSpan t2 = TimeSpan.Parse("00:40:00");
TimeSpan t3 = t1.Add(t2);
Console.WriteLine(t3); // 1.00:10:00
With DateTime:
DateTime d1 = DateTime.Parse("23:30");
DateTime d2 = DateTime.Parse("00:40:00");
DateTime d3 = d1.Add(d2.TimeOfDay);
Console.WriteLine(d3.TimeOfDay); // 00:10:00
Adding two datetimes from strings:
var result = DateTime.Parse(firstDate) + DateTime.Parse(secondDate);
Adding a string time to a datetime:
var result = existingDateTime.Add(TimeSpan.Parse(stringTime);
Adding time as in your example:
var result = TimeSpan.Parse("12:30:22") + TimeSpan.Parse("11:20:22");
Finally, your example as dates (not tested!):
var result = DateTime.Parse("12:30:22") + DateTime.Parse("11:20:22");
Note that this is sloppy coding, but you get the idea. You need to verify somehow that the string is actually parseable.
Not really sure what you're after, but can you not just use the built in functions to C#'s DateTime object?
DateTime myDate = DateTime.Now;
myDate = myDate.AddHours(1);
myDate = myDate.AddMinutes(30);
myDate = myDate.AddSeconds(45);
The problem is more abstract. As already mentioned, in .NET there are two types - DateTime and TimeSpan. The DateTime type represents a specific point in time. It's not an interval of time. It's a specific location in all time since the birth of the Universe. Even if you set the year/month/day components to 0, it will still represent some absolute point in time. Not a length of time.
The TimeSpan on the other hand represents some interval. 1 minute, 2 days, whatever. It's not specified WHEN, just HOW LONG.
So if you were to subtract two DateTime objects you would get a TimeSpan object that specifies how much time there is between them. And if you add a TimeSpan to a DateTime you get another DateTime. But you can't add a DateTime to another DateTime - that would make no sense.
It sounds to me like you should be working with TimeSpans all the time, because you are dealing with lengths of time, not absolute points in time. If you get these lengths from your source as a DateTime then that's actually not correct, and you should convert them to TimeSpans somehow. The parsing method is one way that has been suggested, but you might also try to subtract zero DateTime from it. That might be faster and more culture-independant.
use the TimeSpan structure. you can add TimeSpans together, or you can add a TimeSpan to a DateTime to produce a new DateTime.
You should have a look at TimeSpan.Parse. This converts a string to a TimeSpan object. That way you can do stuff like
TimeSpan a = TimeSpan.Parse(timeStringA)+TimeSpan.Parse(TimeStringB);
To split a string like "00:00:20+00:01:00" look at string.split
stringA = timeSting.split('+')[0];
stringb = timeSting.split('+')[1];
return string.Format("{0}:{1}:{2}", mytimespan.Hours
+ (mytimespan.Days*24),mytimespan.Minutes,mytimespan.Seconds);
static void Main(string[] args)
{
String timeText = "3/23/2015 12:00:13 AM";
String timeText2 = "3/23/2015 1:45:03 AM";
DateTime time = Convert.ToDateTime(timeText);
string temp = time.ToString("HH:mm:ss");
DateTime time2 = Convert.ToDateTime(timeText2);
string temp2 = time2.ToString("HH:mm:ss");
TimeSpan t1 = TimeSpan.Parse(temp);
TimeSpan t2 = TimeSpan.Parse(temp2);
Console.Out.WriteLine(t1 + t2); // 01:45:16
Console.ReadLine();
}