Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C#获取百度时间 #87

Open
landv opened this issue Aug 14, 2024 · 0 comments
Open

C#获取百度时间 #87

landv opened this issue Aug 14, 2024 · 0 comments

Comments

@landv
Copy link
Owner

landv commented Aug 14, 2024

void Main()
{
	var aaa = GetNetDateTime();
	var bbb = Convert.ToDateTime(aaa).ToString("yyyy-MM-dd HH:mm:ss");

	bbb.Dump();
}

public static string GetNetDateTime()
{
	WebRequest request = null;
	WebResponse response = null;
	WebHeaderCollection headerCollection = null;
	string datetime = string.Empty;
	try
	{
		request = WebRequest.Create("https://www.baidu.com");
		request.Timeout = 3000;
		request.Credentials = CredentialCache.DefaultCredentials;
		response = request.GetResponse();
		headerCollection = response.Headers;
		foreach (var h in headerCollection.AllKeys)
		{
			if (h == "Date")
			{
				datetime = headerCollection[h];
			}
		}
		return datetime;
	}
	catch (Exception) { return datetime; }
	finally
	{
		if (request != null)
		{ request.Abort(); }
		if (response != null)
		{ response.Close(); }
		if (headerCollection != null)
		{ headerCollection.Clear(); }
	}
}

时间编码

DateTime dateTime = new DateTime(2024, 8, 12, 18, 0, 0);
string dateTimeString = dateTime.ToString();
byte[] dateTimeBytes = Encoding.UTF8.GetBytes(dateTimeString);
string base64String = Convert.ToBase64String(dateTimeBytes);
Console.WriteLine(base64String);


// 假设已经有经过编码的 Base64 字符串
string base64EncodedDateTime = "MjAyNC0wOC0xMiAxODowMDowMA==";
byte[] data = Convert.FromBase64String(base64EncodedDateTime);
string decodedString = Encoding.UTF8.GetString(data);
// 这里还需要将解码后的字符串转换回 DateTime 类型,具体的转换方式取决于字符串的格式
// 假设字符串格式是 "yyyy-MM-dd HH:mm:ss"
DateTime decodedDateTime = DateTime.Parse(decodedString);
Console.WriteLine(decodedDateTime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant