我正在尝试将日期时间转换为十六进制并将其发送到查询字符串中的另一个页面,并且我正在尝试再次将十六进制转换为日期时间。我已经将日期时间转换为十六进制,如下所示
private string DateToHex(DateTime theDate)
{
string isoDate = theDate.ToString("yyyyMMddHHmmss");
string xDate = (long.Parse(isoDate)).ToString("x");
string resultString = string.Empty;
for (int i = 0; i < isoDate.Length - 1; i++)
{
int n = char.ConvertToUtf32(isoDate, i);
string hs = n.ToString("x");
resultString += hs;
}
return resultString;
}
Run Code Online (Sandbox Code Playgroud)
通过将日期时间转换为十六进制,我得到了这样的结果32303134303631313136353034,在另一个页面中我尝试将十六进制转换为日期时间,如下所示
private DateTime HexToDateTime(string hexDate)
{
int secondsAfterEpoch = Int32.Parse(hexDate, System.Globalization.NumberStyles.HexNumber);
DateTime epoch = new DateTime(1970, 1, 1);
DateTime myDateTime = epoch.AddSeconds(secondsAfterEpoch);
return myDateTime;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过将十六进制转换为日期时间
string sDate = string.Empty;
for (int i = 0; i < hexDate.Length - 1; i++)
{
string ss = hexDate.Substring(i, 2);
int nn = int.Parse(ss, NumberStyles.AllowHexSpecifier);
string c = Char.ConvertFromUtf32(nn);
sDate += c;
}
CultureInfo provider = CultureInfo.InvariantCulture;
CultureInfo[] cultures = { new CultureInfo("fr-FR") };
return DateTime.ParseExact(sDate, "yyyyMMddHHmmss", provider);
Run Code Online (Sandbox Code Playgroud)
它显示了这样的效果Value was either too large or too small for an Int32.。任何解决方案肯定会受到赞赏。任何解决方案都肯定会得到应用
该DateTime值已在内部存储为 a long,因此您不必绕道来创建值long。您可以获取内部值并将其格式化为十六进制字符串:
private string DateToHex(DateTime theDate) {
return theDate.ToBinary().ToString("x");
}
Run Code Online (Sandbox Code Playgroud)
将其转换回来也很简单:
private DateTime HexToDateTime(string hexDate) {
return DateTime.FromBinary(Convert.ToInt64(hexDate, 16));
}
Run Code Online (Sandbox Code Playgroud)
注意:这还会保留该值包含的时区设置DateTime,以及低至 1/10000 秒的完整精度。