字符串扩展支持日期时间格式转换

This commit is contained in:
falcon 2022-10-21 09:13:44 +08:00
parent 641ebc880b
commit 231d546e5d
2 changed files with 29 additions and 13 deletions

View File

@ -1,13 +1,8 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Falcon.SugarApi;
namespace Falcon.SugarApi.Test namespace Falcon.SugarApi.Test
{ {
/// <summary> /// <summary>
/// 字符串扩展方法测试 /// 字符串扩展方法测试
/// </summary> /// </summary>

View File

@ -39,17 +39,38 @@ namespace Falcon.SugarApi
public static string[] SplitStr(this string? str, params char[] splitChars) public static string[] SplitStr(this string? str, params char[] splitChars)
=> str.IsNullOrEmpty() ? Array.Empty<string>() : str.Split(splitChars.Length == 0 ? new char[] { ',', '', ';', '', '.', '。' } : splitChars, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); => str.IsNullOrEmpty() ? Array.Empty<string>() : str.Split(splitChars.Length == 0 ? new char[] { ',', '', ';', '', '.', '。' } : splitChars, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
/// <summary> /// <summary>
/// 将字符串转换为DateTime /// 将字符串按格式转换为时间格式
/// </summary> /// </summary>
/// <param name="str">表示日期时间的字符串</param> /// <param name="str">时间字符串</param>
/// <param name="dateTimeformat">日期时间格式</param> /// <param name="dateTimeFormat">时间格式</param>
/// <returns>一个DateTime对象。如果失败返回null</returns> /// <param name="culture">区域特性.默认CultureInfo.InvariantCulture</param>
public static DateTime ToDateTime([NotNull] this string str, string dateTimeformat = "") { /// <returns>时间</returns>
if (dateTimeformat.IsNullOrEmpty()) { public static DateTime ToDateTime(this string str, string dateTimeFormat = "", CultureInfo? culture = null) {
culture ??= CultureInfo.InvariantCulture;
if (dateTimeFormat.IsNullOrEmpty()) {
return DateTime.Parse(str); return DateTime.Parse(str);
} }
return DateTime.ParseExact(str, dateTimeformat, CultureInfo.CurrentCulture); return DateTime.ParseExact(str, dateTimeFormat, culture);
}
/// <summary>
/// 尝试将特定格式字符串转换为DateTime类型
/// </summary>
/// <param name="str">时间字符串</param>
/// <param name="dateTimeFormat">时间格式</param>
/// <param name="dt">转换后的时间</param>
/// <param name="culture">区域特性.默认CultureInfo.InvariantCulture</param>
/// <returns>成功True失败False</returns>
public static bool TryToDateTime(this string str, string dateTimeFormat, out DateTime dt, CultureInfo? culture = null) {
try {
dt = str.ToDateTime(dateTimeFormat, culture);
return true;
}
catch (Exception) {
dt = default;
return false;
}
} }
} }
} }