DateTimeを可能な限り短いバージョン番号に変換します(URL用)
-
29-10-2019 - |
質問
チャレンジ:「変更された日付」を変換する DateTime
URLの一意性を維持するのに適したバージョン番号 /文字列への画像ファイルの場合、画像の変更ごとに一意のURLが生成されます。バージョン番号 /文字列はできるだけ短くなります。
コードの短さは、これが実際にコードゴルフのステータスの資格がない場合、数/文字列謝罪の短さに続発します:-)
要件
- C#、.NETフレームワークv4
- 出力は、URL内のフォルダー名の有効な文字でなければなりません。
- DateTime Precisionは、最も近い分に減らすことができます。
編集:これは完全に理論的 /パズルではないので、コードゴルフスタックの交換よりもここに保持したいと思いますか?
解決
使用 DateTime.Ticks
プロパティしてから、ベース36番号に変換します。それは非常に短く、URLで使用可能になります。
これは、ベース36に出入りするためのクラスです。
http://www.codeproject.com/kb/cs/base36.aspx
ベース62を使用することもできますが、ベース64の余分な数字の1つは数字を超えています。 +
URLをエンコードする必要があり、それを避けたいと言いました。
他のヒント
OK、答えとコメントを組み合わせて、私は次のことを思いつきました。
注:ゼロのパディングバイトの削除、およびプロジェクトの開始からの開始日の差は、数字のサイズを縮小します。
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;
}
所属していません StackOverflow