locked
Convert DateTime to Base64 string RRS feed

  • Question

  •  

    We have been storing user last access time into cookies and client wanting us to store this information into cookies in the form of Base64 string.

     

    Is there any possibility to convert DateTime into Base64String in C#? please let me know.

    Monday, March 30, 2015 12:05 PM

Answers

  • Seems like an odd requirement. To get a base64 encoded string you first need a string representation of the datetime. You could do ToString with a format provider and then convert that to base64.

    var bytes = System.Text.Encoding.UTF8.GetBytes(DateTime.UtcNow.ToString("F"));
    var base64 = System.Convert.ToBase64String(bytes);
    

    I would use ticks instead of tostring, that would be more reliable.

    var ticks = DateTime.UtcNow.Ticks;
    var date = new DateTime(ticks, DateTimeKind.Utc);
    
    // if it still has to be base64 encoded
    var asLong = DateTime.UtcNow.Ticks;
    var bytes = System.BitConverter.GetBytes(asLong);
    var base64 = System.Convert.ToBase64String(bytes);
    
    var reverseBytes = System.Convert.FromBase64String(base64);
    var reverseLong = System.BitConverter.ToInt64(reverseBytes, 0);
    var reverseDate = new DateTime(reverseLong, DateTimeKind.Utc);
    



    -Igor

    • Proposed as answer by CoolDadTx Monday, March 30, 2015 1:47 PM
    • Marked as answer by Kristin Xie Tuesday, April 7, 2015 1:12 PM
    Monday, March 30, 2015 12:29 PM

All replies

  • How do you declare a Base64 string? I never aware of any Base64 string in C#.

    You can always use ToString() to convert the DateTime to string.

    chanmm


    chanmm

    Monday, March 30, 2015 12:11 PM
  • Seems like an odd requirement. To get a base64 encoded string you first need a string representation of the datetime. You could do ToString with a format provider and then convert that to base64.

    var bytes = System.Text.Encoding.UTF8.GetBytes(DateTime.UtcNow.ToString("F"));
    var base64 = System.Convert.ToBase64String(bytes);
    

    I would use ticks instead of tostring, that would be more reliable.

    var ticks = DateTime.UtcNow.Ticks;
    var date = new DateTime(ticks, DateTimeKind.Utc);
    
    // if it still has to be base64 encoded
    var asLong = DateTime.UtcNow.Ticks;
    var bytes = System.BitConverter.GetBytes(asLong);
    var base64 = System.Convert.ToBase64String(bytes);
    
    var reverseBytes = System.Convert.FromBase64String(base64);
    var reverseLong = System.BitConverter.ToInt64(reverseBytes, 0);
    var reverseDate = new DateTime(reverseLong, DateTimeKind.Utc);
    



    -Igor

    • Proposed as answer by CoolDadTx Monday, March 30, 2015 1:47 PM
    • Marked as answer by Kristin Xie Tuesday, April 7, 2015 1:12 PM
    Monday, March 30, 2015 12:29 PM