DateTime returns wrong date - c#

I'm trying to get today's date
DateTime todayDateTime = new DateTime();
and I'm getting this:
{1/1/0001 12:00:00 AM}.
Why is this happening?

Use this
DateTime date = DateTime.Now;

Using new DateTime() creates a DateTime with a time of "0".
If you want todays date you need to use DateTime.Today if you want a DateTime object with a date of today and a time of 12:00:00 AM or DateTime.Now if you want a DateTime with the day and time of the moment you called DateTime.Now.

According to MSDN, the constructor for DateTime which takes in a long initializes by using the specified number of ticks since January 1st, 0001, so saying new DateTime(0) yields this time, not the current time.
Instead, use the static field DateTime.Now to get a DateTime representing the current system time.

In your question you are just initializing the Variable todayDateTime but you have never assigned (set it). This is why it is date ("null")/ beginning of our time calculations.
To actually get todays Date, you can use the following:
DateTime today = DateTime.Today;

first of all you need to assigned a value in the datetime.
just use something like this :
DateTime today = DateTime.Today;

Related

ASP.NET MVC convert DateTime to UTC to send to API

I need to send a start date and end date to an API in UTC format, I have tried the following:
DateTime startDate = Convert.ToDateTime(start + "T00:00:00Z").ToUniversalTime();
DateTime endDate = Convert.ToDateTime(end + "T23:59:59Z").ToUniversalTime();
But it appears they are not converting to UTC, what would be the proper way to take startDate and endDate and convert them over to UTC?
start is a string and is 2018-08-31 and end date is also a string and is 2018-08-31 I added the times in the code above to cover the full date.
Assuming you want endDate to represent the last possible moment on the given date in UTC:
DateTime startDate = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
DateTime endDate = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
.AddDays(1).AddTicks(-1);
A few other things:
ToUniversalTime converts to UTC from the computer's local time zone (unless .Kind == DateTimeKind.Utc). You should generally avoid it unless the computer's local time zone is relevant to your situation.
In the above code, you need both AssumeUniversal to indicate that the input date is meant to be interpreted as UTC, and AdjustToUniversal to indicate that you want the output value to be kept in terms of UTC and not the computer's local time zone.
UTC is not a "format". Your combined date and time strings would be in ISO 8601 extended format (also RFC 3339 compliant).
Generally, try not to use Convert.ToDateTime. It is equivalent to DateTime.Parse with CultureInfo.CurrentCulture and no DateTimeStyles. That may work for some scenarios, but it is usually better to be more specific.
.AddDays(1).AddTicks(-1) is there to get you to the last representable tick on that date. That allows for inclusive comparison between start and end, however it comes with the disadvantage of not being able to subtract the two values and get a whole 24 hours. Thus, it is usually better to simply track 00:00 of one day to 00:00 of the next day, then use exclusive comparison on the end date. (Only the start date should be compared inclusively.)
In other words, instead of:
2018-08-31T00:00:00.0000000Z <= someValueToTest <= 2018-08-31T23:59:59.9999999Z
Do this:
2018-08-31T00:00:00.0000000Z <= someValueToTest < 2018-09-01T00:00:00.0000000Z
First install below package from NuGet package manager and referenced it in your project:
Install-Package Newtonsoft.Json
Now you can easily use JsonConvert.SerializeObject(object value) method for serialize any objects to Json.
For converting DateTime to UTC use TimeZoneInfo.ConvertTimeToUtc(DateTime dateTime) method.
In your case:
DateTime date = DateTime.Parse("2018-08-31");
DateTime dateTimeToUtc = TimeZoneInfo.ConvertTimeToUtc(date);
string dateInJson = JsonConvert.SerializeObject(dateTimeToUtc);
the variable dateInJson will have value like 2018-08-30T19:30:00Z.
Remove the Z
string start = "2018-08-31";
string end = "2018-08-31";
DateTime startDate = Convert.ToDateTime(start + "T00:00:00");
DateTime endDate = Convert.ToDateTime(end + "T23:59:59");
Console.WriteLine(startDate); // 8/31/2018 12:00:00 (Local)
Console.WriteLine(startDate.ToUniversalTime()); // 8/31/2018 5:00:00 (UTC)
Console.WriteLine(endDate); // 8/31/2018 11:59:59 (Local)
Console.WriteLine(endDate.ToUniversalTime()); // 9/1/2018 4:59:59 (UTC)
In case you are sending dynamic linq like me, you'd need datetime in a text form.
If you are dealing with UTC then:
//specify utc just to avoid any problem
DateTime dateTime = yourDateTime.SetKindUtc();
var filterToSendToApi = $"CreatedTime>={dateTime.ToStringUtc()}"
helpers:
public static string ToStringUtc(this DateTime time)
{
return $"DateTime({time.Ticks}, DateTimeKind.Utc)";
}
public static DateTime SetKindUtc(this DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime;
}
return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}

Merge today's date with a timespan data type value

I'm trying to merge today's date with an existing time value I have stored in a sql server database. Let me give you an example:
ClientTradedTime = "16:52:01" (this is of type timespan)
I want to merge that value with today's date in variable of type DateTime to use it else where, example:
DateTime mydate;
mydate = "2014-02-04 16:52:01" (this is what I want to see when I store it in my database)
How can I solve this problem?
Just Datime.Add() the TimeSpan to the DateTime's Date property and you will get your desired DateTime like:
DateTime updatedDt = mydate.Date.Add(ClientTradedTime);
Consider the following example:
DateTime myDate = DateTime.Now;
TimeSpan ClientTradedTime = new TimeSpan(16, 52, 51);
DateTime updatedDt = myDate.Date.Add(ClientTradedTime);
This will give you:
updatedDt = {04/02/2014 4:52:51 PM}
myDate.Date would give you DateTime with Time set to 00:00:00 and then you can add your TimeSpan to it.

why is datetime not recording time when stored?

When recording a TimeStamp into the the table in the DB why does...
DateTime todaysDate = DateTime.Today;
BookingRecord newBooking = new BookingRecord();
//other code for adding record to db
newBooking.TimeStamp = todaysDate;
why does the record in timeStamp record as : 2013-09-04 00:00:00.000
I want the correct time to display as well?
thanks for reply
Because DateTime.Today is actually supposed to do that. Use DateTime.Now if you want the time information as well.
Edit: of course, it's recommended to use UTC DateTimes for storage in the database anyway, so it's probably best to use DateTime.UtcNow!
DateTime.Today will actually be today's date with the time portion set to 00:00:00:
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
An object that is set to today's date, with the time component set to
00:00:00.
DateTime todaysDate = DateTime.Today;
change to
DateTime todaysDate = DateTime.Now;

un-representable DateTime

I have method which expects two datetime parameters
public void SomeReport(DateTime TimeFrom, DateTime TimeTo)
{
// ommited
TimeFrom.ToString("ddMMyy"), TimeTo.ToString("ddMMyy")));
// ommited
}
When I'm sending this params
DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = new DateTime().AddHours(-1);
This error occured:
System.ArgumentOutOfRangeException : The added or subtracted value results in an un-representable DateTime.
What can be the problem?
new DateTime() is 01/01/0001 00:00:00 which is also DateTime.MinValue.
You are subtracting one hour from that.
Guessing you are trying to subtract an hour from the TimeTo value:
var TimeFrom = TimeTo.AddHours(-1);
new DateTime() returns the minimum representable DateTime; adding -1 hours to this results in a DateTime that can't be represented.
You probably want DateTime TimeFrom = TimeTo.AddHours(-1);
try:
DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = TimeTo.AddHours(-1);
creating a DateTime with new DateTime() gives you a DateTime with DateTime.MinValue... from this you actually can't subtract anything... otherwise you get the exception you got... see MSDN
Look you date or time data .There not enough digits for date or time Example date must be 8 digit 20140604 and time 6 digit like this 180203.For this reason you are getiing error.
i get this error too and find time 18000 and change this to 180000 problem solved.
In your case TimeFrom holds the datetime from which -1 can not be added. You can either invoke
DateTime TimeFrom = TimeTo .AddHours(-1);
or
DateTime TimeFrom = new DateTime().now.AddHours(-1);
Both of them yield the same result.
In my error, I used the time as 24:00 instead of 00:00

Merge 2 DateTime vars into one in C#

I have 2 DateTime variables.
One is: DateTime date //this format is yyyymmdd
Second is: DateTime time // this format is hhmmtt (hour:min:tt)
How can I combine these 2 together? generate one DateTime variable.
var output = new DateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second);
This only works for the two dates you listed, though, where one is the date and one is the time.
You should convert one of the DateTimes to a TimeSpan and add it to the second DateTime. Take the time-only DateTime. You can use its GetTicks method and pass it to a\the TimeSpan constructor.
DateTime day; //assumed set with the correct date
DateTime time; //assumed set with the relevant hour, minute, second
DateTime all = day.Date.Add(new TimeSpan(time.Hour, time.Minute, time.Second));
DateTime date = new DateTime(2012,12,04);
DateTime time = new DateTime(1,1,1,11,20,30);
DateTime combined = date.AddSeconds(TimeSpan.Parse(time.ToShortTimeString()).TotalSeconds);
Console.WriteLine(date);
Console.WriteLine(time);
Console.WriteLine(combined);
04.12.2012 00:00:00
01.01.0001 11:20:30
04.12.2012 11:20:00

Categories