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
}
Related
I have an excel sheet with a date I get out using some JavaScript or VBA (doesn't matter).
Then I end up having a date that looks like this: "Tue Feb 4 00:00:00 UTC+0100 2014"
Are there any build in versions to convert this to C# DateTime? As you can see then I don't use the time part, and thus also don't care about the UTC offset.
Are there any build in versions to convert this to C# DateTime?
Sure! You can use DateTime.TryParseExact or DateTime.ParseExact methods to parse your string.
string s = "Tue Feb 4 00:00:00 UTC+0100 2014";
DateTime dt;
if(DateTime.TryParseExact(s, "ddd MMM d HH:mm:ss 'UTC+0100' yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
But don't use this way when your string have offset values.
In Custom Date and Time Format Strings page; if your string has signed offset, using DateTimeOffset instead of DateTime is recommended.
With DateTime values, the "zzz" custom format specifier represents the
signed offset of the local operating system's time zone from UTC,
measured in hours and minutes. It does not reflect the value of an
instance's DateTime.Kind property. For this reason, the "zzz" format
specifier is not recommended for use with DateTime values.
With DateTimeOffset values, this format specifier represents the
DateTimeOffset value's offset from UTC in hours and minutes.
string s = "Tue Feb 4 00:00:00 UTC+0100 2014";
DateTimeOffset dto;
if(DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss 'UTC'zzz yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Then you can convert this DateTimeOffset to DateTime. Because a DateTime doesn't store any offset value. There is no such a thing like; "a DateTime with an offset as 1 hour"
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 get from an web service a date which is written like that :
"Tuesday, November 12, 2013 8:18:14 AM PST"
or
"Tuesday, November 12, 2013 10:36:03 AM PST"
or
"Wednesday, November 13, 2013 5:15:58 AM PST"
...
This date is stored inside an Array and I would like to sort it. But It does not work properly. So I would like to store this written date in a DateTime or another format supported by the language. Than sort it again. I could be also easier to get only days and hours from a DateTime than using a strstr or something like that.
Is it possible (and how) to convert this written date into a DateTime please ?
PS: I already tried using Convert.DateTime("Wednesday, November 13, 2013 5:15:58 AM PST"). But It didn't work.
Thanks
You need to parse it with format "dddd, MMMM d, yyyy h:m:ss tt 'PST'"
string str = "Wednesday, November 13, 2013 5:15:58 AM PST";
DateTime dt = DateTime.ParseExact(str,
"dddd, MMMM d, yyyy h:m:ss tt 'PST'",
CultureInfo.InvariantCulture);
I have used single d, h and m, for day, hour and month since they will accept both single digit and double digits values.
Becuase Convert.DateTime uses current culture information.
The value argument must contain the representation of a date and time
in one of the formats described in the DateTimeFormatInfo topic.
You can use DateTime.ParseExact method with custom datetime format instead.
string s = "Wednesday, November 13, 2013 5:15:58 AM PST";
DateTime dt = DateTime.ParseExact(s,
"dddd, MMMM d, yyyy h:mm:ss tt 'PST'",
CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
11/13/2013 5:15:58 AM
Here a demonstration.
For more informations, take a look at;
Custom Date and Time Format Strings
If the date will always end with a 3 letter timezone abbreviation the following will work:
string str = "Wednesday, November 13, 2013 5:15:58 AM PST";
DateTime date = DateTime.Parse(str.Substring(0, str.Length - 4));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Date time format from string?
Does anyone know how I could convert the following string to a DateTime value in C# ?
"Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)"
If you only have strings ending with "GMT+0300 (E. Africa Standard Time)", you can try:
string dateString = "Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)";
DateTime date = DateTime.ParseExact(dateString, "ddd MMM dd yyyy HH:mm:ss 'GMT+0300 (E. Africa Standard Time)'", System.Globalization.CultureInfo.InvariantCulture);
The meanings of the specifiers are as follows:
"ddd" The abbreviated name of the day of the week.
"MMM" The abbreviated name of the month.
"dd" The day of the month, from 01 through 31.
"yyyy" The year as a four-digit number.
"HH" The hour, using a 24-hour clock from 00 to 23.
"mm" The minute, from 00 through 59.
"ss" The second, from 00 through 59.
":" The time separator.
"string", 'string' Literal string delimiter.
You can find out more about different format specifiers in the MSDN article named Custom Date and Time Format Strings
Moreover, if you want to parse "GMT+0300 (E. Africa Standard Time)" part too, I think you should implement a way to parse them yourself. I don't think there's a specifier for that.
First of all, you should Africa Standart Time culture info use for yours';
CultureInfo( "af-ZA", false );
But your string is really complex for converting to DateTime. For me it looks imposible to convert to DateTime perfectly. But we can some rehabilitation in your string. For example, if your string was like this; "11/15/2012 00:00:00" you can convert it like this;
using System;
using System.Globalization;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string str = "11/15/2012 00:00:00";
DateTime dt = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", new CultureInfo("af-ZA"));
Console.WriteLine(dt.ToString());
}
}
}
Custom Date and Time Format Strings
DateTime.ParseExact Method
Try this:
DateTime date = DateTime.Parse(yourDateTimeString);
There is no way to handle (E. Africa Standard Time).
Assuming that UTC=GMT you can also get the time zone part, just remove not important parts of your string
string t = Regex.Replace("Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)", "([(].+?[)])", "");
t= t.Replace("GMT", "").Trim();
DateTime a = DateTime.ParseExact(t, "ddd MMM dd yyyy HH:mm:ss zzzz", System.Globalization.CultureInfo.InvariantCulture);
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.