Skip to content

Instantly share code, notes, and snippets.

@kenzauros
Last active May 22, 2018 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenzauros/e59e66fb6b3e76cddd790c4067b51917 to your computer and use it in GitHub Desktop.
Save kenzauros/e59e66fb6b3e76cddd790c4067b51917 to your computer and use it in GitHub Desktop.
yyyymmdd 形式の文字列を DateTime 型に変換する拡張メソッド
using System;
using System.Globalization;
namespace System
{
public static class DateTimeExtensions
{
/// <summary>
/// 指定した日付を "yyyyMMdd" 形式で返します。
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToDbDateString(this DateTime value) => value.ToString("yyyyMMdd");
/// <summary>
/// データベースの "yyyyMMdd" 形式の文字列を <see cref="DateTime"/> 型に変換します。
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static DateTime? ToDateTime(this string value)
=> DateTime.TryParseExact(value, "yyyyMMdd", null, DateTimeStyles.None, out var result)
? (DateTime?)result : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment