简体   繁体   English

如何在C#中将十六进制转换为日期时间

[英]How to convert HEX to Datetime in c#

I am trying to convert datetime to hex and send it to another page in query string and I am trying to convert the Hex to date time again. 我正在尝试将datetime转换为十六进制并将其发送到查询字符串中的另一页,并且我试图再次将hex转换为日期时间。 I have converting datetime to HEX like this 我已经像这样将日期时间转换为十六进制

    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;
    }

By converting Datetime to HEx I got like this 32303134303631313136353034 and in another page I am trying to convert the hex to Date time like this 通过将Datetime转换为HEx,我得到了这样的32303134303631313136353034并且在另一页中,我试图像这样将十六进制转换为Date时间

    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;
    }

I have tried this to Convert HEX to DateTime 我已经尝试过将十六进制转换为DateTime

        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);

It shows the eoor like this Value was either too large or too small for an Int32. 它表明,对于Int32,像这样的Value was either too large or too small for an Int32. . Any solution are surely appretiated. 任何解决方案肯定都值得赞赏。 any solution are sure appratiated 任何解决方案都可以肯定

The DateTime value is already stored internally as a long , so you don't have to make a detour to create a long value. DateTime值已在内部存储为long ,因此您无需绕开就可以创建long值。 You can just get the internal value and format it as a hex string: 您可以获取内部值并将其格式化为十六进制字符串:

private string DateToHex(DateTime theDate) {
  return theDate.ToBinary().ToString("x");
}

Converting it back is as easy: 转换回去很容易:

private DateTime HexToDateTime(string hexDate) {
  return DateTime.FromBinary(Convert.ToInt64(hexDate, 16));
}

Note: This also retains the timezone settings that the DateTime value contains, as well as the full precision down to 1/10000 second. 注意:这还将保留DateTime值包含的时区设置以及低至1/10000秒的全精度。

I can spot two logic errors. 我可以发现两个逻辑错误。

Your DateToHex routine is ignoring the last character. 您的DateToHex例程将忽略最后一个字符。 It should be 它应该是

private string DateToHex(DateTime theDate)
{
    string isoDate = theDate.ToString("yyyyMMddHHmmss");

    string resultString = string.Empty;

    for (int i = 0; i < isoDate.Length ; i++)    // Amended
    {
        int n = char.ConvertToUtf32(isoDate, i);
        string hs = n.ToString("x");
        resultString += hs;

    }
    return resultString;
}

Your routine to convert from hex to string should be advancing two characters at a time , ie 从十六进制转换为字符串的例程应该一次前进两个字符,即

    string hexDate = DateToHex(DateTime.Now);

    string sDate = string.Empty;
    for (int i = 0; i < hexDate.Length - 1; i += 2)       // Amended
    {
        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);

Try this. 尝试这个。 I hope this will solve your purpose. 我希望这可以解决您的目的。 I have tested it and it seems to be working fine. 我已经对其进行了测试,它似乎工作正常。
Convert it to DateTime-> string-> Hex 将其转换为DateTime-> string-> Hex

        string input = DateTime.Now.ToString("yyyyMMddHHmmss");
        string hexValues = "";
        int value = 0;
        char[] values = input.ToCharArray();
        foreach (char letter in values)
        {
            // Get the integral value of the character. 
            value = Convert.ToInt32(letter);
            // Convert the decimal value to a hexadecimal value in string form. 
            hexValues += String.Format("{0:X}", value);
            hexValues += " ";
        }

Now convert it again to HEX-> string-> DateTime 现在再次将其转换为HEX->字符串-> DateTime

        string stringValue = "";            
        string[] hexValuesSplit = hexValues.Split(' ');
        foreach (String hex in hexValuesSplit)
        {
            // Convert the number expressed in base-16 to an integer. 
            if (hex != "")
            {
                value = Convert.ToInt32(hex, 16);
                // Get the character corresponding to the integral value. 
                stringValue += Char.ConvertFromUtf32(value);
            }
        }
        DateTime dt = DateTime.ParseExact(stringValue, "yyyyMMddHHmmss", null);

To convert from hex to time. 从十六进制转换为时间。

Input : 0060CE5601D6CE01 Output : 31-10-2013 06:20:48 输入:0060CE5601D6CE01输出:31-10-2013 06:20:48

        string hex1;
        string[] hex = new string[16];
        hex[0] = hex1.Substring(0, 2);       
        hex[1] = hex1.Substring(2, 2);
        hex[2] = hex1.Substring(4, 2);
        hex[3] = hex1.Substring(6, 2);
        hex[4] = hex1.Substring(8, 2);
        hex[5] = hex1.Substring(10, 2);
        hex[6] = hex1.Substring(12, 2);
        hex[7] = hex1.Substring(14, 2);
        //WE DONOT NEED TO REVERSE THE STRING



        //CONVERTING TO INT SO WE CAN ADD TO THE BYTE[]
        int[] decValue = new int[8];
        for (int i = 0; i < 8; i++)
        {
            decValue[i] = Convert.ToInt32(hex[i], 16);
        }


        //CONVERTING TO BYTE BEFORE WE CAN CONVERT TO UTC 
        byte[] timeByte = new byte[8];

        for (int i = 0; i < 8; i++)
            timeByte[i] = (byte)decValue[i];

        DateTime convertedTime = ConvertWindowsDate(timeByte);
        textBox7.Text = convertedTime.ToString();

    }

    public static DateTime ConvertWindowsDate(byte[] bytes)
    {
        if (bytes.Length != 8) throw new ArgumentException();
        return DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0));
    }

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

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