티스토리 뷰

For strings such as 2012-09-19 01:27:30.000, DateTime.Parse cannot tell what time zone the date and time are from.

DateTime has a Kind property, which can have one of three time zone options:

  • Unspecified
  • Local
  • Utc

NOTE If you are wishing to represent a date/time other than UTC or your local time zone, then you should use DateTimeOffset.


So for the code in your question:

DateTime convertedDate = DateTime.Parse(dateStr);

var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified

You say you know what kind it is, so tell it.

DateTime convertedDate = DateTime.SpecifyKind(
    DateTime.Parse(dateStr),
        DateTimeKind.Utc);
        
        var kind = convertedDate.Kind; // will equal DateTimeKind.Utc
        

Now, once the system knows its in UTC time, you can just call ToLocalTime:

DateTime dt = convertedDate.ToLocalTime();

This will give you the result you require.

-------------------

I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.

// Coordinated Universal Time string from 
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z"; 
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date); 
DateTime utcDateTime = localDateTime.ToUniversalTime();

// ID from: 
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);

-------------------

TimeZone.CurrentTimeZone.ToLocalTime(date);

-------------------

DateTime objects have the Kind of Unspecified by default, which for the purposes of ToLocalTime is assumed to be UTC.

To get the local time of an Unspecified DateTime object, you therefore just need to do this:

convertedDate.ToLocalTime();

The step of changing the Kind of the DateTime from Unspecified to UTC is unnecessary. Unspecified is assumed to be UTC for the purposes of ToLocalTime: http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx

-------------------

I know this is an older question, but I ran into a similar situation, and I wanted to share what I had found for future searchers, possibly including myself :).

DateTime.Parse() can be tricky -- see here for example.

If the DateTime is coming from a Web service or some other source with a known format, you might want to consider something like

DateTime.ParseExact(dateString, 
                   "MM/dd/yyyy HH:mm:ss", 
                                      CultureInfo.InvariantCulture, 
                                                         DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
                                                         

or, even better,

DateTime.TryParseExact(...)

The AssumeUniversal flag tells the parser that the date/time is already UTC; the combination of AssumeUniversal and AdjustToUniversal tells it not to convert the result to "local" time, which it will try to do by default. (I personally try to deal exclusively with UTC in the business / application / service layer(s) anyway. But bypassing the conversion to local time also speeds things up -- by 50% or more in my tests, see below.)

Here's what we were doing before:

DateTime.Parse(dateString, new CultureInfo("en-US"))

We had profiled the app and found that the DateTime.Parse represented a significant percentage of CPU usage. (Incidentally, the CultureInfo constructor was not a significant contributor to CPU usage.)

So I set up a console app to parse a date/time string 10000 times in a variety of ways. Bottom line:
Parse() 10 sec
ParseExact() (converting to local) 20-45 ms
ParseExact() (not converting to local) 10-15 ms
... and yes, the results for Parse() are in seconds, whereas the others are in milliseconds.

-------------------

I'd just like to add a general note of caution.

If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!

Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.

-------------------

@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)

-------------------

Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();
추가 시간을 어떻게 조정합니까?

지정하지 않는 한 .net은 로컬 PC 설정을 사용합니다. 나는 읽었을 것입니다 :

http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

외관상 코드는 다음과 같을 수 있습니다.

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

위에서 언급했듯이 서버가 설정된 시간대를 다시 확인하십시오. IIS의 변경 사항에 안전하게 영향을 미치는 방법에 대한 기사가 인터넷에 있습니다.-------------------
Dana의 제안에 대한 답변 :이제 코드 샘플은 다음과 같습니다.

string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);

원래 날짜는 08/08/20입니다. 종류는 UTC였습니다."convertedDate"와 "dt"는 모두 동일합니다.08/08/21 10:00:26; 종류는 지역이었다-------------------
DataColumn의 DateType 필드가 로컬로 설정 되었기 때문에 자동으로 변경되는 와이어 (웹 서비스에서 클라이언트로)를 통해 푸시되는 데이터 세트에있는 문제가있었습니다. 데이터 세트를 푸시하는 경우 DateType이 무엇인지 확인하십시오.변경하지 않으려면 Unspecified로 설정하십시오.-------------------
Twitter API (상태에 대한 create_at 필드)를 통해 돌아 오는 UTC 날짜에 문제가 있었기 때문에이 질문을 보았습니다. DateTime으로 변환해야합니다. 이 페이지의 답변에있는 답변 / 코드 샘플 중 어느 것도 "문자열이 유효한 DateTime으로 인식되지 않았습니다"오류가 발생하는 것을 막기에 충분하지 않았습니다 (하지만 올바른 답변을 찾는 데 가장 가깝습니다).다른 사람에게 도움이되는 경우를 대비하여 여기에이 링크를 게시하십시오. 필요한 답변은 다음 블로그 게시물에서 찾았습니다.

http://www.wduffy.co.uk/blog/parsing-dates-when-aspnets-datetimeparse-doesnt-work/

-기본적으로 DateTime.Parse 대신 형식 문자열과 함께 DateTime.ParseExact를 사용합니다.

출처
https://stackoverflow.com/questions/180105

댓글
공지사항
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31