如何从Internet获取当前日期和时间 [英] How to get current date and time from Internet

查看:223
本文介绍了如何从Internet获取当前日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能从互联网上获取当前的日期和时间

格式如下20/06/2015 10:30:13 AM

我试过以下代码,



How can i get the current date and time from internet
in format like this 20/06/2015 10:30:13 AM
I was try that below code,

var client = new TcpClient("time.nist.gov", 13);
        using (var streamReader = new StreamReader(client.GetStream()))
        {
            var response = streamReader.ReadToEnd();
            var utcDateTimeString = response.Substring(7, 17);
            Response.Write(response);
            var localDateTime = DateTime.ParseExact(utcDateTimeString, "yy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
            nets = localDateTime.ToString();
        }



工作正常,但没有得到[AM或PM]。


working fine but not getting tt[AM or PM].

推荐答案

那是因为服务器没有返回它:它返回24小时值而不是AM / PM值。

但这没关系,因为一旦你将它处理成DateTime值,它就无关紧要了 - 一个DateTime不需要知道。



AM / PM是一个演示功能 - 它只在你将DatetIme转换为字符串时才有意义 - 你的代码正在使用PC的默认日期设置决定如何格式化日期,因为您没有指定任何特定格式:

That's because the server doesn't return it: it returns a 24 hour value instead of an AM / PM one.
But that's fine, because once you have processed it into a DateTime value it's irrelevant anyway - a DateTime doesn't need to know.

AM/PM is a presentation function - it is only relevant when you convert a DatetIme to a string - and you code is using the default Date setting for your PC to decide how to format the date because you do not specify any particular format:
nets = localDateTime.ToString();



如果你想要一种特定的格式,你必须准确说出你想要的。这可能有所帮助:格式化日期时间以显示 - 格式字符串描述 [ ^ ]



和顺便说一句:我强烈建议你不要这么修剪NIST字符串:你正在剥离前两位数字今年。这意味着您的代码仅适用于当前世纪的日期,因此如果您稍后重用某些代码,它可能会开始为您提供错误的值。 NIST字符串包括全年,因此我将其完整排序,并使用ParseExact处理yyyy-MM-dd hh:mm:ss而不是。


If you want a specific format, you have to say exactly what you want. This may help: Formatting a DateTime for display - format string description[^]

And BTW: I would strongly suggest that you don't trim the NIST string so much: you are stripping out the leading two digits of the year. This means that your code will only work for dates in the current century, so if you later reuse some of that code it could start giving you bad values. the NIST string includes the full year, so I'd string it out complete, and use ParseExact to process "yyyy-MM-dd hh:mm:ss" instead.


这篇关于如何从Internet获取当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆