【问题标题】:Convert DateTime to shortest possible version number (for url)将 DateTime 转换为可能的最短版本号(用于 url)
【发布时间】:2011-11-15 00:43:35
【问题描述】:

挑战:将图像文件的'修改日期'DateTime转换为适合在url中保持唯一性的版本号/字符串,因此图像的每次修改都会生成一个唯一的url,版本号/字符串为尽可能短。

代码的简短性次于数字/字符串的简短性 抱歉,如果这真的不符合代码高尔夫状态:-)

要求

  • C#,.Net 框架 v4
  • 输出必须是 url 中文件夹名称的有效字符。
  • DateTime 精度可以减少到最接近的分钟。

编辑:这不完全是理论上的/谜题,所以我想我宁愿把它留在这里而不是代码高尔夫堆栈交换?

【问题讨论】:

标签: c# c#-4.0 compression code-golf


【解决方案1】:

使用DateTime.Ticks 属性,然后将其转换为基数为 36 的数字。它会很短,并且可以在 URL 上使用。

这是一个用于与 Base 36 相互转换的类:

http://www.codeproject.com/KB/cs/base36.aspx

您也可以使用 base 62,但不能使用 base64,因为 base 64 中除了数字和字母之外的额外数字之一是 +,它需要进行 url 编码,并且您说您希望避免这种情况。

【讨论】:

  • 他可以使用 Base64 并将 /+ 替换为(例如)-_
  • @xanatos,是的,这比创建 base62 转换器更容易,并且比使用 base36 更小。
  • 6 个以 36 为底的字符可以编码未来 27 年的所有 Unix 纪元时间。除非您在遥远的未来有时间或需要比一秒更好的分辨率,否则 base 62 几乎没有实际优势。
【解决方案2】:

好的,结合答案和 cmets 我想出了以下内容。
注意:去除零填充字节,以及从项目开始的开始日期差以减少数字的大小。

    public static string GetVersion(DateTime dateTime)
    {
        System.TimeSpan timeDifference = dateTime - new DateTime(2010, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        long min = System.Convert.ToInt64(timeDifference.TotalMinutes);
        return EncodeTo64Url(min);
    }

    public static string EncodeTo64Url(long toEncode)
    {
        string returnValue = EncodeTo64(toEncode);

        // returnValue is base64 = may contain a-z, A-Z, 0-9, +, /, and =.
        // the = at the end is just a filler, can remove
        // then convert the + and / to "base64url" equivalent
        //
        returnValue = returnValue.TrimEnd(new char[] { '=' });
        returnValue = returnValue.Replace("+", "-");
        returnValue = returnValue.Replace("/", "_");

        return returnValue;
    }

    public static string EncodeTo64(long toEncode)
    {
        byte[] toEncodeAsBytes = System.BitConverter.GetBytes(toEncode);
        if (BitConverter.IsLittleEndian)
            Array.Reverse(toEncodeAsBytes);
        string returnValue = System.Convert.ToBase64String(toEncodeAsBytes.SkipWhile(b=>b==0).ToArray());
        return returnValue;
    }

【讨论】:

  • 注意:这个实现产生 6 个字符的版本号。
猜你喜欢
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2021-01-10
  • 2019-10-03
  • 1970-01-01
  • 2012-05-06
相关资源
最近更新 更多