用C#写一个方法传进来两个string 第一个参数是日期比如2020-09-17 153740第二个参数是秒数比如:100写一个方法让参数一转为DateTime后加上参数二的秒数返回加上秒数后的新日期。要注意string转日期的错误情况也要确保传进来的参数不为空。
你可以使用以下的C#代码来实现这个方法:
using 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方法将秒数字符串转为整数,如果转换失败同样会抛出异常。最后使用DateTime.AddSeconds方法将秒数加到日期上,并返回新的日期。
原文地址: https://www.cveoy.top/t/topic/iF3Y 著作权归作者所有。请勿转载和采集!