简体   繁体   English

从程序中获取错误的日期时间 VB.net

[英]Get False Datetime From The Program VB.net

I have a program that send me a time for any account.我有一个程序可以向我发送任何帐户的时间。

For some people, the program sends the datetime to the database like 2020-05-17 11:33:00 .对于某些人来说,程序将日期时间发送到数据库,如2020-05-17 11:33:00

For some people, the program sends the datetime to the database like 0000-00-00 00:00:00 .对于某些人来说,程序将日期时间发送到数据库,如0000-00-00 00:00:00

A photo to prove this:一张照片证明这一点:

日期时间照片

The code which get the datetime is:获取日期时间的代码是:

Imports System.Globalization
Imports System.Net

    Public Shared Function GetNistTime() As DateTime
        Dim myHttpWebRequest = CType(WebRequest.Create("http://www.microsoft.com"), HttpWebRequest)

        Dim response = myHttpWebRequest.GetResponse()
        Dim todaysDates As String = response.Headers("date")
        Return DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal)
    End Function

So what is the solution?那么解决方法是什么? What can these people install on their machines to prevent this, like install .NET Framework 3.5 ?这些人可以在他们的机器上安装什么来防止这种情况,比如安装 .NET Framework 3.5

I don't know if installing .NET Framework 3.5 can solve this problem!不知道安装.NET Framework 3.5能不能解决这个问题!

I think it can solve the problem because I found it on my PC, and on another PC where I get the datetime like 0000-00-00 00:00:00 doesn't have it installed.我认为它可以解决问题,因为我在我的 PC 上找到了它,而在另一台我得到日期时间为0000-00-00 00:00:00的 PC 上没有安装它。

According to your saying, you should firstly verify if it's just due to problem related to .NET Framework 3.5 installation.根据你的说法,你应该首先验证它是否只是由于.NET Framework 3.5安装相关的问题。 If it isn't, then try this code:如果不是,请尝试以下代码:

Try
    Dim client = New TcpClient("time.nist.gov", 13)
    Dim myDateTime As Date

    Using streamReader = New StreamReader(client.GetStream())
        Dim response = streamReader.ReadToEnd()
        Dim utcDateTimeString = response.Substring(7, 17)

        Dim localDateTime = Date.ParseExact(utcDateTimeString, "yy-MM-dd HH:mm:ss",
                    CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)

        myDateTime = localDateTime
    End Using

    MsgBox(myDateTime.ToString)

    Catch ex As SocketException
        MsgBox("Unable to connect to the time server.", "Connection Failed!")
End Try

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM