I want to get yesterday's date with the time of my choice ( customized time ) and store it in a variable in windows forms C#.
For example: if today's date/Time was 2010-09-25 10:05:03 I want to get the date of the previous day ( 2010-09-24 ) and change the time to 14:30:00 then store it in a variable.
The following codes might help:
DateTime.Now; // it gives you today's Date and current Time
DateTime.Today.AddHours(14:5); // it gives you the current date with customized time (`14:30:00`).
DateTime.Now.AddDays(-1); // it gives you the previous day
Please help me how to achieve this. Thank you.
You can combine the statements like this
var dateTime = DateTime.Now.AddDays(-1).Date.AddHours(14.5);
But remember DateTime objects are immutable so every time you modify a DateTime object you have to assign it to a variable.
You can get DateTime.Now.Date to cut time off, and then add time components.
var result = DateTime.Now.Date.AddDays(-1)
.AddHours(14)
.AddMinutes(30)
.AddSeconds(21);
It will result in 14:30:21 of the previous day.
Related
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.
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.
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
}
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.
In C# if I want to parse a datetime, but some times I just have either a date and not a time component or no date but a time component, how would I do this? Usually when you leave out the time component, it automatically assumes that the time is 12:00AM. But I don't want this. If the time component is missing then I just want the DateTime to store a date only and the leave the time component off.
The value of a DateTime internally is just an UInt64 (ulong in C#) that stores the number of ticks since some date in the past, so whether you like it or not, the time component will always be there.
If you only need to display certain parts, just use any of the format strings (examples are for "en-us" culture):
DateTime.Now.ToString("d"); // 5/26/2009
DateTime.Now.ToString("t"); // 4:56 PM
The complete reference: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
It's not possible to have a DateTime without a time component. You could store a boolean flag along with it in a struct to store data about existence of that component. However, there's no way to use the automatic parsing routine to distinguish between a DateTime string with a time specified as 12:00 PM and a nonexistent one.
If it really bugs you you can always create a wrapper class that can hide the time portions of the datetime class.
No you will have the time component no matter what. The best you can do is access the Date property on your DateTime object if you really have to.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime by definition stores a date and a time such that it cannot just represent one of them without representing the other. If you only want the date (or only the time), parse out the information you need and discard the rest of it.
As mentioned before DateTime will always have a Date and a Time part of it if you only want a single part use the way described by the others
DateTime date = DateTime.Parse("2009-11-30);
date.Year; = 2009
date.Month; = 11
date.Day; = 30
date.Hour; = 0
and so on
The thing you must be aware is that all of these methods will only return an integer.
If you want to know all the possible ways to parse a string John Sheehan has put together a great Cheat Sheet wit all possible ways to parse and manipulate dates, and other strings for that matter.
You could have a class that stores a DateTime and determines if the time was ever set or if just the date was set and return values accordingly.
Use
DateTime date = new DateTime();
date = DateTime.Parse("1/1/2001");
to set the date, then use
date.ToShortDateString();
or
date.Year;
date.Month;
date.Day;
to get what you need. Hope that helps!
A DateTime object is always stores a date + a time, not just one. You can always choose to work only with the date part, i.e. only use properties like Year, Month, DayOfWeek. But underneath there will aways be some stored time.
It is very dangerous to assume that the date portion of a DateTime is necessarily the date you are expecting. As pointed-out, DateTime always includes and considers the time aspect, even when you don't see it.
This is a big problem when you have data stored in different time-zones (and particularly if knowledge of that offset is not also kept, because it is assumed that what is being stored is a Date, not a date-with-time).
You may store a birthdate as '01/01/2000 00:00:00' during Summer-Time, which then is stored in UCT as '31/12/1999 23:00:00'. When you then read that birth-date later, the date portion is now a day early.
Best to create your own type. Strange that Microsoft didn't think it worth having a Date type.