using Microsoft.AspNetCore.Http;
namespace DS.Module.Core.Helpers;
///
///
///
public static partial class Extensions
{
///
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
///
public static long ParseToLong(this object obj)
{
try
{
return long.Parse(obj.ToString());
}
catch
{
return 0L;
}
}
#region 转换为double
///
/// 将object转换为double,若转换失败,则返回0。不抛出异常。
///
///
///
public static double ParseToDouble(this object obj)
{
try
{
return double.Parse(obj.ToString());
}
catch
{
return 0;
}
}
#endregion 转换为double
///
/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。
///
///
///
public static DateTime ParseToDateTime(this string str)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return DateTime.MinValue;
}
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 DateTime.MinValue;
}
}
//
// 摘要:
// 将 IFormFile 转换成 byte[]
//
// 参数:
// formFile:
public static byte[] ToByteArray(this IFormFile formFile)
{
long length = formFile.Length;
using Stream stream = formFile.OpenReadStream();
byte[] array = new byte[length];
stream.Read(array, 0, (int)length);
return array;
}
}