외부 서버에서 인터넷을 통해 날짜 시간을 취하는 기능을 사용하고 있습니다. 다음은 사용자 PC 날짜 시간 설정에 의존하지 않고 날짜와 시간을 얻기 위해 사용하는 기능입니다.
using NodaTime;
using NodaTime.Text;
using System.IO;
using System.Globalization;
public static DateTime GetFastestNISTDate()
{
var result = DateTime.MinValue;
DateTime utcDateTime = DateTime.MinValue;
// Initialize the list of NIST time servers
// http://tf.nist.gov/tf-cgi/servers.cgi
string[] servers = new string[] {
"nist1-ny.ustiming.org",
"nist1-nj.ustiming.org",
"nist1-pa.ustiming.org",
"time-a.nist.gov",
"time-b.nist.gov",
"nist1.aol-va.symmetricom.com",
"nist1.columbiacountyga.gov",
"nist1-chi.ustiming.org",
"nist.expertsmi.com",
"nist.netservicesgroup.com"
};
// Try 5 servers in random order to spread the load
Random rnd = new Random();
foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
{
try
{
// Connect to the server (at port 13) and get the response
string serverResponse = string.Empty;
using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
{
serverResponse = reader.ReadToEnd();
}
// If a response was received
if (!string.IsNullOrEmpty(serverResponse))
{
// Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
string[] tokens = serverResponse.Split(' ');
// Check the number of tokens
if (tokens.Length >= 6)
{
// Check the health status
string health = tokens[5];
if (health == "0")
{
// Get date and time parts from the server response
string[] dateParts = tokens[1].Split('-');
string[] timeParts = tokens[2].Split(':');
// Create a DateTime instance
utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
// Convert received (UTC) DateTime value to the local timezone
result = utcDateTime.ToLocalTime();
//return result;
return utcDateTime;
// Response successfully received; exit the loop
}
}
}
}
catch
{
// Ignore exception and try the next server
}
}
//return result;
return utcDateTime;
}
여기 variable result
에는 현지 날짜 시간이 있지만 현지 날짜 시간 변수를 넣고 result
다른 시간대를 지정하고 Noda libraray가 해당 시간대의 현지 날짜와 시간을 반환 하는 Nodatime 라이브러리를 사용해야 합니다.
그것을 달성하는 방법을 안내하십시오. 이 URL을 방문 하지만 다른 시간대를 기반으로 다른 datetime을 얻기 위해 외부 서버에서 가져온 Nodatime 라이브러리와 현지 시간을 함께 통합하는 방법이 아직 명확하지 않습니다.
약간의 샘플 코드에 대한 도움을 찾고 있습니다.
var wc = GetFastestNISTDate();
var pattern = InstantPattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
var parseResult = pattern.Parse(wc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
if (!parseResult.Success)
throw new InvalidDataException("...whatever...");
var instant = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
시간대 번역이 작동하지 않습니다. 이 함수에서 올바른 날짜를 얻었고 GetFastestNISTDate();
다음으로 첫 번째 UTC 시간을 기반으로 다른 시간대의 현지 날짜와 시간을 얻으려고 시도하지만 코드는 런던에 대해 잘못된 시간을 반환합니다. 나는 내가 코드를 실수하고 있다고 생각한다. 누구나보고 도움을받을 수 있습니다. 감사
Nodatime 라이브러리에서 달성하고 싶은 것과 동일합니다.
var wc = GetFastestNISTDate();
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(wc, cstZone);
위의 코드는 다소 적절한 시간을 제공합니다. nodatime 라이브러리를 사용하여 마지막 두 줄을 바꾸는 방법을 알려주십시오. 감사
var wc = GetFastestNISTDate();
Instant now = Instant.FromDateTimeUtc(wc);
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
@John은 위의 코드가 괜찮다고 말해줍니다.
Don't convert the UTC DateTime to a local version - it's pointless and confusing
Use Instant.FromDateTimeUtc to convert a UTC DateTime to an instant
GetFastestNISTDate() returning datetime instance and here we just create noda instance from utc datetime using like this code `Instant now = Instant.FromDateTimeUtc(wc);`
문제를 해결합니까?
@Matt Johnson : thanks a lot for redirecting me to a good library.
i would definitely like to work with that library to achieve my task. before
use your library i have some question.
포인트 1
이 루틴에서 잘못된 점 GetFastestNISTDate();
은 루틴이 몇 개의 NIST 시간 서버를 쿼리하고 utctime을 가져 오는 것입니다.
utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
이 루틴 GetFastestNISTDate();
은 utcDateTime을 반환했습니다 .... utc 시간이 아니 었습니까?
내가 GetFastestNISTDate();
루틴 을 호출했을 때 나는 이 루틴이 DateTime.MinValue
예상되지 않은 결과를 반환 하는 것을 알았습니다. 나는 왜 그것이 because NIST time servers
바쁘거나 차단되었거나 그 시간에 타임 아웃이 발생 했는지 이해할 수있었습니다 .
NodaTime.NetworkClock
를 사용하는 경우 기본적으로 쿼리 할 NTP 서버를 알고 싶습니다.내가 사용 NodaTime.NetworkClock
하면 언젠가 잘못된 날짜 또는 null 날짜를 얻 NTP server is busy/block
거나 시간 초과가 발생할 가능성이 있습니까?
var instant = NetworkClock.Instance.Now;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
lbldate.Text = zonedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
lbltime.Text = zonedDateTime.ToString("hh:mm:ss", CultureInfo.InvariantCulture);
귀하의 GetFastestNISTDate
기능은 사용 낮 프로토콜을 기본적으로 사용되지 않으며 그 결과는 어떤 특정 형식으로되어 있기 때문에 기계 상호 작용을 의미하지 않는다 -. NIST 의 문서 조차도 사용자 가 주간 대신 NTP 를 사용하도록 강력히 권장합니다 .
여기 에서 NTP 클라이언트의 간단한 C # 구현을 찾을 수 있습니다 .
작업을 더 쉽게하기 위해이 클라이언트를 NodaTime.IClock
. 코드는 여기 GitHub에 있습니다 . NuGet에서 설치하기 만하면됩니다 .
Install-Package NodaTime.NetworkClock
그런 다음 다음을 사용하는 것처럼 사용할 수 있습니다 SystemClock
.
var instant = NetworkClock.Instance.Now;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다