用批处理文件实现同步到个人时间服务器,[已解决]批处理搭配curl命令如何实现:同步日期和时间到本地电脑?...

/*&cls

@echo off

set "netpath=%systemroot%\Microsoft.NET\Framework"

for /f "delims=" %%a in ('dir /ad /b "%netpath%\v?.*"') do (

if exist "%netpath%\%%a\csc.exe" (

set "cscpath=%netpath%\%%a\csc.exe"

goto :0

)

)

echo;未安装.Net Framework 2.0及其上版本组件或相关程序丢失&pause&exit

:0

if not exist $SetDateTime.exe ("%cscpath%" /out:$SetDateTime.exe "%~f0")

echo;

echo;手动运行$SetDateTime.exe

ping -n 4 0 >nul&exit

*/

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Text.RegularExpressions;

using System.Diagnostics;

using System.Threading;

class SetDateTime

{

private static byte[] result = new byte[512];

static void Main(string[] args)

{

IPAddress ip = IPAddress.Parse(Dns.GetHostAddresses("time.nist.gov")[0].ToString());

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

try

{

clientSocket.Connect(new IPEndPoint(ip, 13));

}

catch

{

Console.WriteLine("连接服务器失败,程序将自动退出!");

Thread.Sleep(3000);

return;

}

int receiveLength = clientSocket.Receive(result);

Match dtstr = Regex.Match(Encoding.ASCII.GetString(result, 0 ,receiveLength), @"\d+(-\d+){2}\s\d+(:\d+){2}");

DateTime dt = DateTime.ParseExact(dtstr.ToString(), "yy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture).AddHours(8);

Console.WriteLine("服务器当前日期时间为:{0}", dt.ToString());

Process proc = new Process();

proc.StartInfo.FileName = "cmd.exe";

proc.StartInfo.Arguments = "/c date "+dt.ToShortDateString().ToString()+"&time "+dt.ToLongTimeString().ToString();

proc.StartInfo.UseShellExecute = false;

proc.StartInfo.RedirectStandardError = true;

proc.Start();

string err = proc.StandardError.ReadToEnd();

Console.WriteLine(err != ""?err:"同步日期时间完成,请按任意键退出!");

Console.ReadKey(true);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值