Every time that I create a non-nullable datetime in my mvc3 application it defaults to now(), where now is current date with current time. I would like to default it to today's date with 12am as the time.
I'm trying to default the time in my mvc...but...the following isn't setting to todays date #12am. Instead it defaults to now with current date and time.
private DateTime _Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0);
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
How can I set to 12am for the current date for non-nullable datetime?
You can use the Date property of the DateTime object - eg
DateTime midnight = DateTime.Now.Date;
So your code example becomes
private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...
var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
I believe you are looking for DateTime.Today. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
Only need to set it to
DateTime.Now.Date
Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();
It shows
"2017-04-08 00:00:00"
on my machine.
Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.
double utcOffset= 10.0; // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;
var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);
Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:
return (dateOne.Value.Date - dateTwo.Value.Date).Days;
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00
Related
I have a variable with date time which I have to set on a specific date by these rukles and scenarios:
The API that I connect to has a daily limit and once that limit is reached I have to wait until NEXT DAY until 9:10 AM CEST <= This is very important
So I've been simply doing this:
var localTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"));
var tomorrowAt0910 = localTime.AddDays(1).Date + new TimeSpan(9, 10, 0);
And I have realized that this code has a bug, because I can have following scenarios:
Let's say my application would expire on 30th of July at 15:00 PM in which case this logic up there would be VALID
BUT
We have a next following scenario which is more likely to happen:
Application expires on 31st of July 5:00 AM, in which case this logic is faulty because RENEWAL DATE will be set to 1st of August 9:10AM WHICH IS BAD
If the application expires in this second case, I should set the date to same day and few hours difference (from 5AM to 9AM)
How could I do this?
It sounds like what you really want is to say:
Find the current time in Central Europe
Find 9:10am on the same date
If 9:10am is after the current time, add a day
So something like:
// No need to do this more than once
private static readonly TimeZoneInfo centralEuropeZone =
TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time")
private static DateTime GetUtcResetTime()
{
// Using UtcNow to make it clear that the system time zone is irrelevant
var centralEuropeNow = TimeZoneInfo.ConvertTime(DateTime.UtcNow, centralEuropeZone);
var centralEuropeResetTime = centralEuropeNow.Date + new TimeSpan(9, 10, 0);
if (centralEuropeResetTime <= centralEuropeNow)
{
centralEuropeResetTime = centralEuropeResetTime.AddDays(1);
}
return TimeZoneInfo.ConvertTimeToUtc(centralEuropeResetTime, centralEuropeZone);
}
I've made that return a UTC DateTime so that no other code needs to worry about which zone it's in.
Check if the expire date is less that the current date, if so add one day.
DateTime expireDate = new DateTime(2018, 7, 30, 22, 0, 0); //for testing
DateTime tomorrowAt0910 = DateTime.Now.Date.AddHours(9).AddMinutes(10);
if (expireDate.Date < DateTime.Now.Date)
{
tomorrowAt0910.AddDays(1);
}
private void StartAuction()
{
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
}
I am able to set the date,month and year but I want the hours,minutes and seconds to setup automatically to the current time of the day. for example if the current time is 15:24, I want the user to add the date which could be 21/03/2013 and then I want the time to be 15:24:00 and not 00:00:00 as it currently does.
Any suggestions?
Well you can use DateTime.Now to get the current time, then take the TimeOfDay from that and add it to the Date of your existing DateTime:
private void StartAuction()
{
DateTime closeDate = DateTime.Parse(Console.ReadLine());
DateTime closeDateAtCurrentTime = closeDate.Date + DateTime.Now.TimeOfDay;
...
}
(I'm explicitly using the Date property so that even if the user does enter a time as well, it's basically stripped.)
As a blatant plug, you might also want to consider using my Noda Time library, which separates out the ideas of "date", "time" and "date/time" into different types. (As well as "local" values vs ones where you know the UTC offset or the time zone.)
var now = DateTime.Now;
var date = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
First you need to parse with DateTime.Parse what you read from command line.
Then, you can do that using DateTime.Now.TimeOfDay like;
DateTime closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + DateTime.Now.TimeOfDay;
You could do
closeDate = DateTime.Parse(Console.ReadLine() + " " + DateTime.Now.TimeOfDay);
Which works, but does look a little roundabout and I wouldn't recommend it considering you're converting from a time format to a string and then back to a time format again. Lots of immutable objects being created, there.
There are other options, including to parse the date, as you do, and then add TimeOfDay to it.
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + Date.Now.TimeOfDay;
You can do this:
closeDate = DateTime.Parse(Console.ReadLine())
.Add(DateTime.Now - DateTime.Today);
Well how about this little function:
public static DateTime ChangeTime(DateTime dateTime)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
DateTime.Now.Millisecond,
DateTime.Now.Kind);
}
This is a possible solution:
store DateTime.Now in a variable
var date = DateTime.Now;
Then u can access the Hours, Minutes and Seconds like this:
date.Hour;
date.Minute;
date.Second;
The following code crashes and burns and I don't understand why:
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse("1332958778172");
Console.Write(dt.AddSeconds(d));
Can someone tell me what's going on? I just can't seem to be able to figure out why...
EDIT
This value comes back from the Salesforce REST API and from what I understand it's a Unix epoch time stamp. "The time of token issue, represented as the number of seconds since the Unix epoch (00:00:00 UTC on 1 January 1970)."
SOLUTION
Salesforce REST API is in fact sending milliseconds back for the issued_at field when performing the OAuth request when they say they're sending seconds...
As others have said, the problem is that the value is too large.
Having looked over it, I believe it represents milliseconds since the Unix epoch, not seconds so you want:
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse("1332958778172"); // Or avoid parsing if possible :)
Console.Write(dt.AddMilliseconds(d));
Either that, or divide by 1000 before calling AddSeconds - but obviously that will lose data.
The value you are adding results in a date outside of the valid range of dates that a DateTime supports.
DateTime supports 01/01/0001 00:00:00 to 31/12/9999 23:59:59.
A simple calculation of 1332958778172/3600/24/365 gives 42267 years.
I think the double value is genuinely too large. It represents just over 42,267 years (if my maths is correct), and DateTime.MaxValue is 23:59:59.9999999, December 31, 9999
DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
Console.Write(dt.AddSeconds(1332958778172D));
Except that...
1332958778172/60/60/24/365 = 42,267 years... which DateTime can only go up to 23:59:59.9999999, December 31, 9999
I had a similar issue where I was required to add a configurable timespan to a datetime.
If the configuration is not correct I have to assume the 'worst scenario' : MaxValue.
I solved it by implementing an extension to DateTime (still in test phase) :
/// <summary>
/// Removes a timespan from a date, returning MinValue or MaxValue instead of throwing exception when if the resulting date
/// is behind the Min/Max values
/// </summary>
/// <returns></returns>
public static DateTime SafeAdd(this DateTime source, TimeSpan value)
{
// Add or remove ?
if (value.Ticks > 0)
{
// add
var maxTicksToAdd = DateTime.MaxValue - source;
if (value.Ticks > maxTicksToAdd.Ticks)
return DateTime.MaxValue;
}
else
{
var maxTicksToRemove = source - DateTime.MinValue;
// get the value to remove in unsigned representation.
// negating MinValues is impossible because it would result in a value bigger than MaxValue : (-32768 .. 0 .. 32767)
var absValue = value == TimeSpan.MinValue ? TimeSpan.MaxValue : -value;
if (absValue.Ticks > maxTicksToRemove.Ticks)
return DateTime.MinValue;
}
return source + value;
}
Looks like this timestamp is in milliseconds, try below code it should work fine.
DateTime nDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
double epoch = 1585008000000;
DateTime rDate = nDateTime.AddMilliseconds(epoch);
In my case I had to consume an api object as a double and convert the unix time to a DateTime:
DateTime Date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Double.Parse("1596225600000"));
I have an instance of DateTime that I get from my database, I want to subtract it from DateTime.Now and find out if 4 hours were passed. How do I do that?
Also when should i use DateTime.UTCNow or DateTimeOffset
You can use the subtraction operator to get a TimeSpan:
private static readonly TimeSpan MinimumTime = TimeSpan.FromHours(4);
...
if ((dateFromDatabase - DateTime.Now) > MinimumTime)
{
...
}
As for whether you need UTCNow or Now... it will depend on what happens to time zones when you fetch the data from the database. DateTime is not terribly clear on this front :(
If you can fetch the value as a DateTimeOffset to start with, then you can use DateTimeOffset.Now instead and it should be simpler to work out any time zone issues.
DateTime.Subtract
First Google hit..
Try this:
bool fourHoursPassed = date.AddHours(4) < DateTime.Now;
or this to actually perform a subtraction:
bool fourHoursPassed = (DateTime.Now - date).TotalHours > 4;
DateTime.Subtract
or
DateTime myDateTime = someValue;
TimeSpan ts = DateTime.Now -myDateTime;
if(ts.Hours>=4)
{
doSomething();
}
Hope it helps.
DateTime dt = new DateTime(2011, 07, 10);
DateTime dob = new DateTime(1987, 07, 10);
You can simply subtract as:
TimeSpan age = dt - dob;
i have a datetime(in utc) saved in database and i also know the utc offset in the following format.
-03:00:00
how to convert this to a DateTime
This simplest way to apply an "offset" to a DateTime that you already have is to create a TimeSpan structure which holds your offset value, and then simply "add" the offset to the original DateTime value.
For example:
DateTime utcDateTime = DateTime.Parse("29 July 2010 14:13:45");
TimeSpan offSet = TimeSpan.Parse("-03:00:00");
DateTime newDateTime = utcDateTime + offSet;
Console.WriteLine(newDateTime);
This results in the following output:
29/07/2010 11:13:45
which is the original time (29 July 2010 14:13:45) minus 3 hours (the offset - -03:00:00).
Note that this technique is merely performing simple arithmetic with your DateTime value and does not take any time zones into account.
The problem you are likely running into is that most DB drivers when fetching from the database will create the DateTime with DateTimeKind.Unspecified, which may not convert to UTC properly even when you use ToUniversalTime. To get arround this I use an extension method like this:
public static DateTime ToSafeUniversalTime(this DateTime date) {
if(date != DateTime.MinValue && date != DateTime.MaxValue) {
switch(date.Kind) {
case DateTimeKind.Unspecified:
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, DateTimeKind.Utc);
break;
case DateTimeKind.Local:
date = date.ToUniversalTime();
break;
}
}
return date;
}