I have the following C# code that creates a DateTime, enters it into a table, and then queries that table:
DateTime date = DateTime.Now;
DateTest newRecord = new DateTest {
dateColumn = date
};
db.DateTest.AddObject(newRecord);
db.SaveChanges();
IQueryable<DateTest> records =
from d in db.DateTest
select d;
If I break the code at this point, and take a look at the objects in the debugger, I get this for the date object:
Date {11/22/2011 12:00:00 AM} System.DateTime
Day 22 int
DayOfWeek Tuesday System.DayOfWeek
DayOfYear 326 int
Hour 8 int
Kind Local System.DateTimeKind
Millisecond 345 int
Minute 59 int
Month 11 int
Second 33 int
Ticks 634575491733450602 long
TimeOfDay {08:59:33.3450602} System.TimeSpan
Year 2011 int
And I get this for the record retrieved from the table:
Date {11/22/2011 12:00:00 AM} System.DateTime
Day 22 int
DayOfWeek Tuesday System.DayOfWeek
DayOfYear 326 int
Hour 8 int
Kind Unspecified System.DateTimeKind
Millisecond 347 int
Minute 59 int
Month 11 int
Second 33 int
Ticks 634575491733470000 long
TimeOfDay {08:59:33.3470000} System.TimeSpan
Year 2011 int
As you can see, they're off by a couple milliseconds.
Can anyone explain why this is, and how I can fix it? I need to be able to query for records exactly matching a DateTime object in memory, but this behaviour is causing my queries to come up empty handed.
The resolution of the DateTime field in SQL Server is different from the one of the DateTime .NET class.
From MSDN - datetime (Transact-SQL):
Accuracy: Rounded to increments of .000, .003, or .007 seconds
So, in your case, the milliseconds get rounded up to the .007, giving .3470000 instead of .3450602.
The DateTime2 SQL Server datatype has a resolution of 100 nano seconds, like .NET, so may be a suitable replacement.
I think it is because you are using a DateTime column in the database. It does not have the same precision as the DateTime type in .NET. Try using column type DateTime2 in the database instead.
Related
DateTime Date;
DateTime.TryParse("01.09.2015", (new CultureInfo("en-CA")), DateTimeStyles.None, out Date);
Windows 7 SP1 Result:
Date {01.09.2015 00:00:00} System.DateTime
Date {01.09.2015 00:00:00} System.DateTime
Day 1 int
DayOfWeek Tuesday System.DayOfWeek
DayOfYear 244 int
Hour 0 int
Kind Unspecified System.DateTimeKind
Millisecond 0 int
Minute 0 int
Month 9 int
Second 0 int
Ticks 635766624000000000 long
TimeOfDay {00:00:00} System.TimeSpan
Year 2015 int
Windows Server 2012 R2 Standard Result:
Date {1/9/2015 12:00:00 AM} System.DateTime
Date {1/9/2015 12:00:00 AM} System.DateTime
Day 9 int
DayOfWeek Friday System.DayOfWeek
DayOfYear 9 int
Hour 0 int
Kind Unspecified System.DateTimeKind
Millisecond 0 int
Minute 0 int
Month 1 int
Second 0 int
Ticks 635563584000000000 long
TimeOfDay {00:00:00} System.TimeSpan
Year 2015 int
Why are these differences for day and month ? Any patch needed ?
DateTime.TryParse uses standard date and time formats of supplied culture. Looks like this en-CA culture has different formats with Windows 7 and Windows Server 2012.
Seems like Windows 7 using dd/MM/yyyy format and Windows Server 2012 using MM/dd/yyyy format.
This settings can change over .NET Framework version and/or OS version. Don't worry. If you want to parse your string exactly, you can use DateTime.ParseExact or DateTime.TryParseExact methods to supply exact format for your string.
string s = "01.09.2015";
DateTime dt;
if(DateTime.TryParseExact(s, "dd.MM.yyyy", CultureInfo.GetCultureInfo("en-CA"),
DateTimeStyles.None, out dt))
{
// 1 September 2015
}
or
string s = "01.09.2015";
DateTime dt;
if(DateTime.TryParseExact(s, "MM.dd.yyyy", CultureInfo.GetCultureInfo("en-CA"),
DateTimeStyles.None, out dt))
{
// 9 January 2015
}
I want minutes part when i subtract two time values.
I am subtracting current time with 11:30 PM and the result i need in minutes.
I am trying the following code in c#.
TimeSpan eTs = new TimeSpan(23, 30, 00);
int min = System.DateTime.Now.Minute - eTs.Minutes;
but its giving wrong values.
Any help?
Thanks in advance.
It gives wrong value because you are substracting ints. It could even give negative numbers. You should substract the TimeSpan from the DateTime, which gives you another DateTime and use it's Minute property.
var eTs = new TimeSpan(23, 30, 00);
var min = (System.DateTime.Now - eTs).Minute;
EDIT
I am subtracting current time with 11:30 PM and the result i need in
minutes.
No, you are substracting 23 hours and 30 minutes from the current date time.
If you want to know how much minutes have passed since 11:30 PM (what day/month/year), you should:
var min = (System.DateTime.Now - somePastDate).TotalMinutes; //somePastDate must be a DateTime
Do you wanna subtract 2 dateTime and Get the total in minutes try this:
DateTime data = DateTime.Now;
DateTime data2 = DateTime.Now.AddDays(-2);
TimeSpan sub = data - data2;
Console.WriteLine(sub.TotalMinutes);
Or If you wanna subtract minutes from a datetime try this
TimeSpan eTs = new TimeSpan(23, 30, 00);
DateTime data2 = System.DateTime.Now.AddMinutes(-eTs.TotalMinutes);
Console.WriteLine(data2);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I tried to convert 1368463365 which is an int field in sql server database with the following code
public static DateTime JulianToDateTime(int julianDate)
{
int RealJulian = julianDate + 1900000;
int year = Convert.ToInt32(RealJulian.ToString().Substring(0, 4));
int DoY = Convert.ToInt32(RealJulian.ToString().Substring(4));
DateTime d = new DateTime(year, 1, 1);
return d.AddDays(DoY - 1);
}
It looks like you have a Unix timestamp there. The value 1368463365 would be equivalent with 13 May 2013 16:42:45 GMT.
A Unix timestamp is simply the number of seconds since midnight January 1st, 1970 UTC/GMT. So you can convert it to a regular DateTime like this:
public static DateTime UnixTimeToDateTime(long timestamp)
{
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds((double)timestamp);
dateTime = dateTime.ToLocalTime(); // Change GMT time to your timezone
return dateTime;
}
Adapted from this answer. Usage:
long timestamp = 1368463365;
Console.WriteLine(UnixTimeToDateTime(timestamp));
Result (on my Dutch computer, in UTC+2):
13-5-2013 18:42:45
Your input is not a julian date. It's a timestamp. 1368463365 refers to Mon, 13 May 2013 16:42:45 GMT.
You can use following method to get DateTime from timestamp:
public static DateTime UnixTimeStampToDateTime( int unixTimeStamp )
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0);
dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dtDateTime;
}
The number 1368463365 is Unix timestamp and it's number of seconds since 1/1/1970. In that case what you have to do is to just add this timestamp to DateTime representing the the date 1/1/1970 00:00:00.
Example code from another SO question:
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0);
dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dtDateTime;
}
Check this SO question for reference.
And BTW, there's a little place for mistake here, but if you want to check what date such timestamp represents, you can check it online with this converter.
Insofar as I know, Julian Date can mean
The count of days since 1 January 4713 BCE at 12:00:00 pm (Noon) UTC in the Julian Calendar, which is 24 November 4714 BCE in the Gregorian calendar. Today 18 February 2014 is JD 2456706 (for at least part of the day.)
The ordinal day of the year (e.g. 31 December 2013 is 2013365; 31 December 2012 is 2012366.
None of these are 10 digits. For conversion to/from the former, see http://aa.usno.navy.mil/faq/docs/JD_Formula.php (your tax dollars at work...or at least my tax dollars at work).
Conversion to/from the ordinal date form should be pretty obvious:
string julianDate = "2014323" ; // the 323rd day of 2014
int year = int.Parse( julianDate.substring(0,4) ) ;
int ordinalDayNumber = int.Parse( julianDate.substring(4,3) ) ;
DateTime dt = new DateTime(year,1,1).AddDays( ordinalDayNumber - 1 ) ;
The unix time is a the number of seconds since midnight January 1, 1970 UTC.
DateTime UnixTimeToDateTime(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
}
I have an int representing a number of Gregorian days from Year Zero (thanks, Erlang). How do I convert this to a DateTime object? I can't create a DateTime(0,0,0), and Convert.DateTime(int) throws an invalid cast.
If you have a number, and you know the date that it represents (from Erlang), you can calculate the offset from any date you choose. Preferred is a base date in the zone that the results will be in, this will minimize calender conversion effects. (The Gregorian calendar is valid from about 1600).
If you know that offset, you can use the choosen date as the base for future calculations.
Example:
I want my offset date to be: 1/1/2000. This will be the date that I calculcate from.
I know number 37892 from erlang is actually 1/1/1970 (this is an example).
Then I can calculate the offset:
var myBaseDate = new DateTime(2000,1,1);
var exampleNrOfDays = 37892;
var exampleDate = new DateTime(1970,1,1);
var offset = exampleDate - myBaseDate;
var offsetInDays = exampleNrOfDays - (int)offset.TotalDays;
// Now I can calculate
var daysFromErlang = 30000; // <= example
var theDate = myBaseDate.AddDays(daysFromErlang - offsetInDays);
This shows how to calculate number of days from a given date. http://dotnetperls.com/datetime-elapsed
if day zero is 0/0/0 then it is 365+30+1 day before DateTime.Min which is 1/1/1. So you can subtract days from year zero by 365+30+1 and add to DateTime.Min
Now Month 1 is January which is 31 days but what is Month 0? I assumed it is 30 days.
With 0, you probably mean 0:00 on the 1st of January, year 1. There is no year 0 in the gregorian calendar as far as i know.
If the above is right, you can just do
DateTime date = new DateTime();
date.AddDays(numberOfDays);
because the default constructor 'DateTime()' returns the "zero" DateTime object.
See the DateTime reference for more informations.
I am not sure if you are aware of this, but there is a Calendar object in System.Globalization. Not only that but there is a GregorianCalendar object as well.
so try this:
GregorianCalendar calendar = new GregorianCalendar();
DateTime minSupportedDateTime = calendar.MinSupportedDateTime;
//which is the first moment of January 1, 0001 C.E.
DateTime myDate = minSupportedDateTime.AddDays(55000);
//this is when you add the number of days you have.
Thanks,
Bleepzter
PS. Don't forget to mark my answer if it has helped you solve your problem! Thanks.
How can I convert a number between 1 and 7 into a DateTime object in C# which represents the day of the week? The numbers are coming from a XML file which I am parsing. I am retrieving each instance of a field containing a number between 1 and 7 which represents a day of the week between Sunday and Saturday.
I would assume casting to a DayOfWeek object would give you a day of the week
DayOfWeek day = (DayOfWeek)myInt;
As far as a DateTime object goes, the object represents a specific day, not necessarily a random day of the week. You may try adding a # of days to a specific date if this is what you're trying to achieve.
http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
In order to get a DateTime, you'd need a specific range of dates that you want the weekday to fall under (since a DateTime is a specific date and time, and a weekday isn't).
There is a DayOfWeek enumeration (whose values actually range from 0-6). If all you need is something to represent the day of the week, then you should be able to cast your int to a DayOfWeek like..
DayOfWeek myDay = (DayOfWeek)yourInt;
If you need an actual DateTime, you'll need a start date. You could then do...
DateTime myDate = startDate.AddDays(
(int)startDate.DayOfWeek >= yourInt ?
(int)startDate.DayOfWeek - yourInt :
(int)startDate.DayOfWeek - yourInt + 7);
This will give you a DateTime for the next occuring instance of the day of the week you're describing.
DayOfWeek.Sunday is zero, so you could start with an arbitrary fixed date that you know to be Sunday, and add a value between 0 and 6:
public DateTime GetDayOfWeek(int dayOfWeek)
{
if (dayOfWeek < 0 || dayOfWeek > 6) throw new ArgumentOutOfRangeException(...);
// 4 January 2009 was a Sunday
return new DateTime(2009,1,4).AddDays(dayOfWeek);
}
I'm not sure why you would want this though.
If you only want it to get a localized version of the day of the week as in:
GetDayOfWeek(3).ToString("dddd"); // Gets name of day of week for current culture
an alternative would be to use DateTimeFormatInfo.DayNames or DateTimeFormatInfo.AbbreviatedDayNames for the culture you want.
A DateTime instance represents alway a complete date and cannot only represent a day of the week. If the actual date does not matter, take any monday (assuming 0 represents monday) and just add the number of the day.
Int32 dayOfWeek = 3;
// date represents a thursday since 2009/04/20 is a monday
DateTime date = new DateTime(2009, 04, 20).AddDays(dayOfWeek);
Else I agree with Adam Robinson's answer - if you just want to hold the day of a week, stick with the DayOfWeek enum (zero is sunday) instead of using an integer.