102 lines
3.0 KiB
C#
102 lines
3.0 KiB
C#
using NaiBa.Util.Extension;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace AllBase.Extension
|
|
{
|
|
public static class Extensions
|
|
{
|
|
public static long? ParseToNullableLong(this object obj)
|
|
{
|
|
if (obj == null)
|
|
return null;
|
|
|
|
try
|
|
{
|
|
string str = obj.ParseToString();
|
|
if (string.IsNullOrEmpty(str))
|
|
{
|
|
return null;
|
|
}
|
|
return long.Parse(str);
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static int? ParseToNullableInt(this object str)
|
|
{
|
|
if (str == null)
|
|
return null;
|
|
|
|
try
|
|
{
|
|
return Convert.ToInt32(str);
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static decimal? ParseToNullableDecimal(this object str)
|
|
{
|
|
try
|
|
{
|
|
if (str == null)
|
|
return null;
|
|
return decimal.Parse(str.ToString());
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static DateTime? ParseToNullableDateTime(this string str)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrWhiteSpace(str))
|
|
{
|
|
return null;
|
|
}
|
|
if (str.Contains("-") || str.Contains("/"))
|
|
{
|
|
return DateTime.Parse(str);
|
|
}
|
|
else
|
|
{
|
|
int length = str.Length;
|
|
switch (length)
|
|
{
|
|
case 4:
|
|
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 6:
|
|
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 8:
|
|
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 10:
|
|
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 12:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
|
case 14:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
default:
|
|
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
}
|