C#日期时间计算:安全地将秒数添加到日期字符串
C#日期时间计算:安全地将秒数添加到日期字符串
本文提供了一个C#方法,可以将以字符串形式传入的秒数添加到日期字符串中,并返回新的日期时间。该方法包含了对输入参数的验证和错误处理,以确保代码的健壮性。
**代码示例:**csharpusing System;
public class Program{ public static void Main(string[] args) { string dateStr = '2020-09-17 15:37:40'; string secondsStr = '100'; DateTime result = AddSecondsToDateTime(dateStr, secondsStr); Console.WriteLine(result); } public static DateTime AddSecondsToDateTime(string dateStr, string secondsStr) { DateTime date; int seconds; // 检查参数是否为空 if (string.IsNullOrEmpty(dateStr) || string.IsNullOrEmpty(secondsStr)) { throw new ArgumentException('参数不能为空'); } // 尝试将日期字符串转为DateTime类型 if (!DateTime.TryParse(dateStr, out date)) { throw new ArgumentException('日期格式不正确'); } // 尝试将秒数字符串转为整数 if (!int.TryParse(secondsStr, out seconds)) { throw new ArgumentException('秒数格式不正确'); } // 添加秒数并返回新日期 return date.AddSeconds(seconds); }}
代码解释:
-
参数检查: 该方法首先检查传入的日期字符串和秒数字符串是否为空。如果任一参数为空,则抛出
ArgumentException异常,提示'参数不能为空'。 -
日期字符串转换: 使用
DateTime.TryParse方法尝试将日期字符串转换为DateTime类型。如果转换失败,则抛出ArgumentException异常,提示'日期格式不正确'。 -
秒数字符串转换: 使用
int.TryParse方法尝试将秒数字符串转换为整数。如果转换失败,则抛出ArgumentException异常,提示'秒数格式不正确'。 -
计算新日期: 使用
DateTime.AddSeconds方法将转换后的秒数添加到DateTime对象中,并返回新的日期时间。
使用方法:
将日期字符串和秒数字符串作为参数传递给 AddSecondsToDateTime 方法即可。例如:csharpstring dateStr = '2020-09-17 15:37:40';string secondsStr = '100';DateTime newDateTime = AddSecondsToDateTime(dateStr, secondsStr);
总结:
这个C#方法提供了一种安全可靠的方式来将秒数添加到日期字符串中,并包含了对输入参数的验证和错误处理,确保代码的健壮性。
原文地址: https://www.cveoy.top/t/topic/fK7d 著作权归作者所有。请勿转载和采集!