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.
Related
I am trying to insert time on my asp.net project.
RequestUpdateEmployeeDTR requestUpdateEmployeeDTR = new RequestUpdateEmployeeDTR();
requestUpdateEmployeeDTR.AttendanceDeducID = int.Parse(txtAttendanceDeducID.Text);
requestUpdateEmployeeDTR.TimeInChange = txtTimeOutChange.Text;
requestUpdateEmployeeDTR.TimeOutChange = txtTimeOutChange.Text;
TimeInChange and TimeOutChange are DateTime data types. But I am inserting a time data type. How can I convert that into a time data type using C#? Thanks!
The .NET Framework does not have a native Time data type to represent a time of day. You will have to decide between one of the three following options:
Option 1
Use a DateTime type, and ignore the date portion. Pick a date that's outside of a normal range of values for your application. I typically use 0001-01-01, which is conveniently available as DateTime.MinValue.
If you are parsing a time from a string, the easiest way to do this is with the DateTimeStyles.NoCurrentDateDefault option. Without this option, it would use today's date instead of the min date.
DateTime myTime = DateTime.Parse("12:34", CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault);
// Result: 0001-01-01 12:34:00
Of course, if you prefer to use today's date, you can do that. I just think it confuses the issue because you might be looking to apply this to some other date entirely.
Note that once you have a DateTime value, you can use the .TimeOfDay property to get at just the time portion, represented as a TimeSpan, which leads to option 2...
Option 2
Use a TimeSpan type, but be careful in how you interpret it. Understand that TimeSpan is first and foremost a type for representing an elapsed duration of time, not a time of day. That means it can store more than 24 hours, and it can also store negative values to represent moving backwards in time.
When you use it as a time of day, you might be inclined to think of it as "elapsed time since midnight". This, however, will get you into trouble because there are days where midnight does not exist in the local time zone.
For example, October 20th 2013 in Brazil started at 1:00 AM due to daylight saving time. So a TimeSpan of 8:00 on this day would actually have been only 7 hours elapsed since 1:00, not 8 hours elapsed since midnight.
Even in the United States, for locations that use daylight saving time, this value is misleading. For example, November 3rd 2013 in Los Angeles had a duplicated hour for when DST rolled back. So a TimeSpan of 8:00 on this day would actually had 9 hours elapsed since midnight.
So if you use this option, just be careful to treat it as the representative time value that matches a clock, and not as "time elapsed since midnight".
You can get it directly from a string with the following code:
TimeSpan myTime = TimeSpan.Parse("12:34", CultureInfo.InvariantCulture);
Option 3
Use a library that has a true "time of day" type. You'll find this in Noda Time, which offers a much better API for working with date and time in .NET.
The type that represents a "time of day" is called LocalTime, and you can get one from a string like this:
var pattern = LocalTimePattern.CreateWithInvariantCulture("HH:mm");
LocalTime myTime = pattern.Parse("12:34").Value;
Since it appears from your question that you are working with time and attendance data, I strongly suggest you use Noda Time for all your date and time needs. It will force you to put more thought into what you are doing. In the process, you will avoid the pitfalls that can come about with the built-in date/time types.
If you are storing a Time type in your database (such as SQL server), that gets translated as a TimeSpan in .Net. So if you go with this option, you'll need to convert the LocalTime to a TimeSpan as follows:
TimeSpan ts = new TimeSpan(myTime.TickOfDay);
I am currently using the following date filter in my WebAPI application:
json.SerializerSettings.Converters.Add(
new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy hh:mm" });
I started to use this as my front end could not understand the dates. If I remember correctly it was due to the way milliseconds were formatted with too many digits.
What I need is to get the date into a format like this:
1288323623006
Can someone suggest how I can do this using the serializer. Is this different from the default?
You don't want to use IsoDateTimeConverter at all - you possibly want to use JavaScriptDateTimeConverter. That will convert it into new Date(...) with the right value - but I believe it really will include the new Date(...) part. If you don't want that, you'll probably need to write your own converter.
It shouldn't be too hard to write a converter - although you need to decide how to handle the different kinds of DateTime. For example, if you're asked to convert a DateTime with a Kind of Unspecified, do you want to assume it's actually already in UTC, or already in the system local time zone, or something else?
Once you've got an appropriate "instant" in time, you just need to find the number of milliseconds between that and the Unix epoch (1st January 1970 00:00:00, UTC) and convert that number of milliseconds into a string.
I think that's what you want
private static readonly long DatetimeMinTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
long b = (long)((Calendar1.SelectedDate).ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000;
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
}
In PHP, you can write the following:
date_default_timezone_set("UTC");
How do I do I write this in C#?
Also, how do I write this:
declare(ticks=1);
in C#?
In c#, the timezone is built into the DateTime structure, so you should not need to set the default. Instead when you are manipulating DateTime instances you use the UTC version of methods. For example, in the constructor you can specify if the date supplied is local or UTC.
With regards to the second question, are you just wanting the syntax of
int ticks = 1; // or
var ticks = 1;
If you are trying to add a time period to a date, you should use a TimeSpan, along the lines of:
TimeSpan ticks = new TimeSpan(1);
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.