Iswar
Iswar

Reputation: 2301

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. 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

    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

        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.. Any solution are surely appretiated. any solution are sure appratiated

Upvotes: 0

Views: 6909

Answers (4)

Silver
Silver

Reputation: 39

To convert from hex to time.

Input : 0060CE5601D6CE01 Output : 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));
    }

Upvotes: 0

Guffa
Guffa

Reputation: 700562

The DateTime value is already stored internally as a long, so you don't have to make a detour to create a long value. 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.

Upvotes: 5

Ricky
Ricky

Reputation: 2374

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

        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

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

Upvotes: 0

sgmoore
sgmoore

Reputation: 16077

I can spot two logic errors.

Your DateToHex routine is ignoring the last character. 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);

Upvotes: 1

Related Questions