Getting current time but then incrementing it? - c#

Current project: To make a time program in C# with two classes Time and ExtendedTime Time is just the normal time and ExtendedTime has the time zone.
When you start the program I need to click a button and get the current time but there is an option to change the time zone. This in turn changes the time and also has an option to increment the time by so many hours and or minutes.
Currently, this is what my displayTime method in the Time class looks like:
public virtual string displayTime()
{
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
MessageBox.Show(time.ToString(format)); // Write to console
return time.ToString(format);
}//end of displayTime
Which isn't bad except that everytime I call it NO MATTER WHAT it will always tell me the current time because of DateTime.Now
I'm not totally sure how to get around that. I'm sure there is a one time deal i can do to do this but not sure of the syntax.

You can use the TimeSpan class to manipulate the DateTime class. For example:
DateTime now = DateTime.Now;
DateTime twoHoursLater = now + new TimeSpan(2,0,0);
DateTime twoDaysLater = now + new TimeSpan(2,0,0,0);
If you're using a user-supplied time, such as one from a textbox, you can use
DateTime userSuppliedTime = DateTime.Parse(myTextbox.Text);
Which will give you a DateTime that corresponds to whatever the user enters. Be warned, however, that if the user types in something that the system does not recognize as valid, this will throw an exception.

DateTime.Add and DateTime.Subtract should suffice.
DateTime adjusted = DateTime.Now.Add(TimeSpan.FromMinutes(30));

You get current time became you have no code that manipulates that DateTime field.
To apply time zones, look into TimeZoneInfo class.

You really should look into using the DateTimeOffset structure, which works well for this kind of thing.

Related

What does DateTime now = DateTime.Now; do in C#?

I found out how to get the current date and time as variables (right?) in C# thanks to this thread with the code
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];
However I'm not sure what the first line does. After some thinking I suppose it calls the current date and time data from the computer and applies/tells it to the program.
By the way, I'm a noob at programming and new to C#.
The first line
DateTime now = DateTime.Now;
takes the current time, and stores it in a variable. The reason it's done is to make sure that subsequent calls of GetDateTimeFormats are performed on a variable representing the same time. If you call DateTime.Now several times, you may get a different time each time that you make a call.
For example, if you do
string date = DateTime.Now.GetDateTimeFormats('d')[0];
string time = DateTime.Now.GetDateTimeFormats('t')[0];
very close to midnight, the date and time portions may belong to different dates.
Yes, it does exactly what you think it does.
You created a variable called now (type DateTime) and assigned it to DateTime.Now which is a special static property of DateTime that:
Gets a DateTime object that is set to the current date and time on
this computer, expressed as the local time.
(MSDN)
So you have the date and time that line of code was run stored off in the now variable. Simple as that.

DateTime.Date get me Date and 12:00 AM

I have already seen this.
I am going to get only Date from a DateTime variable and in this way I used this code:
DateTime Start = GetaDateTime();
String Day = Start.ToString("yyyy/MM/dd");
DateTime d = Convert.ToDateTime(Day);
But when I use d.Date it gives me '2014-08-23 12:00 AM'
Actually I should not get 12:00AM any more????
Actually I should not get 12:00AM any more????
Why not? A DateTime has no notion of whether it's meant to be a date or a date and time, or any sort of string formatting. It's just a point in time (and not even quite that, given the odd Kind part of it).
Note that a simpler way of getting a DateTime which is the same as another but at midnight is just to use Date to start with:
DateTime start = Foo();
DateTime date = start.Date;
No need for formatting and then parsing.
There's no .NET type representing just a date. For that, you'll want something like my Noda Time project, which has a rather richer set of date/time types to play with.

How to determine if it has been 60-days or not by comparing DateTime?

To provide a TRIAL period to my application when the user first runs the application I save the FirstRunTime like this:
string sFirstRunDate = DateTime.Today.ToShortDateString();
saveInfo.saveFirstRun(sFirstRunDate ); // saves as a string to a text file
Now everytime I run the application I want to see if it has been more then 60 days and if so terminate (60-day trial only). How can I do that compare?
string sFirstRunDate = saveInfo.getFirstRun(); // returns the string I saved earlier
DateTime dtFirstRunDate = DateTime.Parse(sFirstRunDate); // makes it a DateTime
DateTime now = DateTime.Today.ToShortDateString(); // why am I doing this?
So how can I take the two dates and compare them to see if it has been more then 60 days or not?
Thanks,
The following should do it:
var elapsed = DateTime.Today.Subtract(dtFirstRunDate);
if (elapsed.TotalDays > 60)
{
// trial expired
}
The advantage of this is when the trial hasn't expired you can tell them how far they are into their trial (using elapsed.TotalDays).
TimeSpan t = DateTime.Now.Subtract(dtFirstRunDate);
if (t.Days > 60)
{
//do something
}
Try
if(DateTime.Parse(sFirstRunDate).AddDays(60) < DateTime.Now) {
// trial has expired
}
This just takes the first run, adds 60 days to it, if the current time is greater than the time first run + 60 days, the trial is over.
All other answers are technically going to work for you, but they are wrong on a larger scale. Please read further.
// why am I doing this?
This tells me that you do not quite grasp the concepts you're trying to apply. Let's go one by one.
string sFirstRunDate = DateTime.Today.ToShortDateString();
There are two problems with that. First the DateTime.Today returns the local date/time. Never ever use local date/time for any kind of calculations because local time is not consistent. Daylight changes, travel through time zones, all affect the local time that is returned by this property. What you should use instead is DateTime.UtcNow.Date to get the current UTC time which is the global clock not affected by any of the aforementioned problems.
Second problem is the ToShortDateString method. It converts the date/time using current culture. Did you know that in other parts of the world, the date is reported as 'DD/MM/YYYY', or 'YYYY-MM-DD'? What will happen if the user changes current locale? To avoid those problems you should use the ToString(CultureInfo.InvariantCulture) method.
The correct code to serialize the first run date is
string sFirstRunDate = DateTime.UtcNow.Date.ToString(CultureInfo.InvariantCulture);
DateTime now = DateTime.Today.ToShortDateString(); // why am I doing this?
To calculate the difference between two dates, first you need to acquire those two dates. The first one would be the saved first run date, and the second would be today. You did the first part by deserializing the first run date into DateTime structure. For the second part you just need the current date, you don't need to serialize it into string. So
DateTime today = DateTime.UtcNow.Date;
Now that you have two dates, you have an array of options on how to actually get the difference. Any of the other answers do that part just fine. I personally like Timothy Walters' answer as it has a nice side effect of giving your the days left for trial. It will look like:
DateTime dtFirstRunDate = DateTime.Parse(saveInfo.getFirstRun());
DateTime today = DateTime.UtcNow.Date;
var elapsed = today.Subtract(dtFirstRunDate);
if (elapsed.TotalDays > 60)
{
// trial expired
}

Difference between System.DateTime.Now and System.DateTime.Today

Can anyone explain the difference between System.DateTime.Now and System.DateTime.Today in C#.NET? Pros and cons of each if possible.
DateTime.Now returns a DateTime value that consists of the local date and time of the computer where the code is running. It has DateTimeKind.Local assigned to its Kind property. It is equivalent to calling any of the following:
DateTime.UtcNow.ToLocalTime()
DateTimeOffset.UtcNow.LocalDateTime
DateTimeOffset.Now.LocalDateTime
TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local)
TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local)
DateTime.Today returns a DateTime value that has the same year, month, and day components as any of the above expressions, but with the time components set to zero. It also has DateTimeKind.Local in its Kind property. It is equivalent to any of the following:
DateTime.Now.Date
DateTime.UtcNow.ToLocalTime().Date
DateTimeOffset.UtcNow.LocalDateTime.Date
DateTimeOffset.Now.LocalDateTime.Date
TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local).Date
TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local).Date
Note that internally, the system clock is in terms of UTC, so when you call DateTime.Now it first gets the UTC time (via the GetSystemTimeAsFileTime function in the Win32 API) and then it converts the value to the local time zone. (Therefore DateTime.Now.ToUniversalTime() is more expensive than DateTime.UtcNow.)
Also note that DateTimeOffset.Now.DateTime will have similar values to DateTime.Now, but it will have DateTimeKind.Unspecified rather than DateTimeKind.Local - which could lead to other errors depending on what you do with it.
So, the simple answer is that DateTime.Today is equivalent to DateTime.Now.Date.
But IMHO - You shouldn't use either one of these, or any of the above equivalents.
When you ask for DateTime.Now, you are asking for the value of the local calendar clock of the computer that the code is running on. But what you get back does not have any information about that clock! The best that you get is that DateTime.Now.Kind == DateTimeKind.Local. But whose local is it? That information gets lost as soon as you do anything with the value, such as store it in a database, display it on screen, or transmit it using a web service.
If your local time zone follows any daylight savings rules, you do not get that information back from DateTime.Now. In ambiguous times, such as during a "fall-back" transition, you won't know which of the two possible moments correspond to the value you retrieved with DateTime.Now. For example, say your system time zone is set to Mountain Time (US & Canada) and you ask for DateTime.Now in the early hours of November 3rd, 2013. What does the result 2013-11-03 01:00:00 mean? There are two moments of instantaneous time represented by this same calendar datetime. If I were to send this value to someone else, they would have no idea which one I meant. Especially if they are in a time zone where the rules are different.
The best thing you could do would be to use DateTimeOffset instead:
// This will always be unambiguous.
DateTimeOffset now = DateTimeOffset.Now;
Now for the same scenario I described above, I get the value 2013-11-03 01:00:00 -0600 before the transition, or 2013-11-03 01:00:00 -0700 after the transition. Anyone looking at these values can tell what I meant.
I wrote a blog post on this very subject. Please read - The Case Against DateTime.Now.
Also, there are some places in this world (such as Brazil) where the "spring-forward" transition happens exactly at Midnight. The clocks go from 23:59 to 01:00. This means that the value you get for DateTime.Today on that date, does not exist! Even if you use DateTimeOffset.Now.Date, you are getting the same result, and you still have this problem. It is because traditionally, there has been no such thing as a Date object in .Net. So regardless of how you obtain the value, once you strip off the time - you have to remember that it doesn't really represent "midnight", even though that's the value you're working with.
If you really want a fully correct solution to this problem, the best approach is to use NodaTime. The LocalDate class properly represents a date without a time. You can get the current date for any time zone, including the local system time zone:
using NodaTime;
...
Instant now = SystemClock.Instance.Now;
DateTimeZone zone1 = DateTimeZoneProviders.Tzdb.GetSystemDefault();
LocalDate todayInTheSystemZone = now.InZone(zone1).Date;
DateTimeZone zone2 = DateTimeZoneProviders.Tzdb["America/New_York"];
LocalDate todayInTheOtherZone = now.InZone(zone2).Date;
If you don't want to use Noda Time, there is now another option. I've contributed an implementation of a date-only object to the .Net CoreFX Lab project. You can find the System.Time package object in their MyGet feed. Once added to your project, you will find you can do any of the following:
using System;
...
Date localDate = Date.Today;
Date utcDate = Date.UtcToday;
Date tzSpecificDate = Date.TodayInTimeZone(anyTimeZoneInfoObject);
Time. .Now includes the 09:23:12 or whatever; .Today is the date-part only (at 00:00:00 on that day).
So use .Now if you want to include the time, and .Today if you just want the date!
.Today is essentially the same as .Now.Date
The DateTime.Now property returns the current date and time, for example 2011-07-01 10:09.45310.
The DateTime.Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000.
The DateTime.Today property actually is implemented to return DateTime.Now.Date:
public static DateTime Today {
get {
DateTime now = DateTime.Now;
return now.Date;
}
}
DateTime.Today represents the current system date with the time part set to 00:00:00
and
DateTime.Now represents the current system date and time
I thought of Adding these links -
A brief History of DateTime - By Anthony Moore by BCL team
Choosing between Datetime and DateTime Offset - by MSDN
Do not forget SQL server 2008 onwards has a new Datatype as DateTimeOffset
The .NET Framework includes the DateTime, DateTimeOffset, and
TimeZoneInfo types, all of which can be used to build applications
that work with dates and times.
Performing Arithmetic Operations with Dates and Times-MSDN
Coming back to original question , Using Reflector i have explained the difference in code
public static DateTime Today
{
get
{
return DateTime.Now.Date; // It returns the date part of Now
//Date Property
// returns same date as this instance, and the time value set to 12:00:00 midnight (00:00:00)
}
}
private const long TicksPerMillisecond = 10000L;
private const long TicksPerDay = 864000000000L;
private const int MillisPerDay = 86400000;
public DateTime Date
{
get
{
long internalTicks = this.InternalTicks; // Date this instance is converted to Ticks
return new DateTime((ulong) (internalTicks - internalTicks % 864000000000L) | this.InternalKind);
// Modulo of TicksPerDay is subtracted - which brings the time to Midnight time
}
}
public static DateTime Now
{
get
{
/* this is why I guess Jon Skeet is recommending to use UtcNow as you can see in one of the above comment*/
DateTime utcNow = DateTime.UtcNow;
/* After this i guess it is Timezone conversion */
bool isAmbiguousLocalDst = false;
long ticks1 = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks;
long ticks2 = utcNow.Ticks + ticks1;
if (ticks2 > 3155378975999999999L)
return new DateTime(3155378975999999999L, DateTimeKind.Local);
if (ticks2 < 0L)
return new DateTime(0L, DateTimeKind.Local);
else
return new DateTime(ticks2, DateTimeKind.Local, isAmbiguousLocalDst);
}
}
DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
DateTime dt = DateTime.Now;// gives today date with current time
DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time
DateTime.Today is DateTime.Now with time set to zero.
It is important to note that there is a difference between a DateTime value, which represents the number of ticks that have elapsed since midnight of January 1, 0000, and the string representation of that DateTime value, which expresses a date and time value in a culture-specific-specific format:
https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx
DateTime.Now.Ticks is the actual time stored by .net (essentially UTC time), the rest are just representations (which are important for display purposes).
If the Kind property is DateTimeKind.Local it implicitly includes the time zone information of the local computer. When sending over a .net web service, DateTime values are by default serialized with time zone information included, e.g. 2008-10-31T15:07:38.6875000-05:00, and a computer in another time zone can still exactly know what time is being referred to.
So, using DateTime.Now and DateTime.Today is perfectly OK.
You usually start running into trouble when you begin confusing the string representation with the actual value and try to "fix" the DateTime, when it isn't broken.
DateTime.Now.ToShortDateString() will display only the date part

C#, how do I make a clock work with added hours?

Using Visual Studio 2008 (C#) I have to make a working clock (digital) with the current time zone hour, and a few more with different time zones, like new york, etc.
inside the form I put 2 labels (for the clocks) and a timer, inside the timer I put this code:
timer1.Interval = 1000;
label1.Text = DateTime.Now.ToLongTimeString();
DateTime myDateTime = DateTime.Now;
TimeSpan myTimeSpan = new TimeSpan(2, 0, 0);
DateTime myDateTime8 = myDateTime + myTimeSpan;
label2.Text = ("" + myDateTime8);
the part with the timespan does add 2 hours to the clock, however, instead of just the actually clock I also get the date on it's left, like for example:
"17-05-2011 22:38:00"
I need to know how can I add/subtract hours and only show the clock.
Instead of adding a timespan, simply call the AddHours method:
myDateTime.AddHours(2).ToLongTimeString();
myDateTime.ToShortTimeString() will return you only time
or as Tejs mentioned you can use ToLongTimeString() that I guess more suits your requirement.
For adding or subtracting hours you can use dateTime.AddHours(even hours in negative) or for subtracting you can also use dateTime.Subtract(time to subtract)
Using the .ToString() method of the timespan method allows you to output the date in any format you want. See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
For your time zone needs, use an approach similar to the one suggested in this MSDN article. Notably:
Use ConvertTimeToUtc to get UTC time before performing any arithmetics.
Perform required arithmetics.
Convert back to local time using TimeZoneInfo.ConvertTime.
To get just the time part of a DateTime, use DateTime.ToShortTimeString(). Note that this is culture-aware, so if you want a fixed format, consider using DateTime.ToString() to specify a format.

Categories