我如何才能改变我的DateTime变量“s”的时间?

DateTime s = some datetime;

当前回答

试试这个

var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;

其他回答

设定一天的结束:

date = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59);

好了,我要深入介绍我的建议,一个扩展方法:

public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
    return new DateTime(
        dateTime.Year,
        dateTime.Month,
        dateTime.Day,
        hours,
        minutes,
        seconds,
        milliseconds,
        dateTime.Kind);
}

然后调用:

DateTime myDate = DateTime.Now.ChangeTime(10,10,10,0);

重要的是要注意,这个扩展返回一个新的日期对象,所以你不能这样做:

DateTime myDate = DateTime.Now;
myDate.ChangeTime(10,10,10,0);

但是你可以这样做:

DateTime myDate = DateTime.Now;
myDate = myDate.ChangeTime(10,10,10,0);

由于DateTime是不可变的,所以当需要更改日期组件时,必须创建一个新实例。不幸的是,没有内置功能来设置DateTime实例的各个组件。

使用以下扩展方法

public static DateTime SetPart(this DateTime dateTime, int? year, int? month, int? day, int? hour, int? minute, int? second)
{
    return new DateTime(
        year ?? dateTime.Year,
        month ?? dateTime.Month,
        day ?? dateTime.Day,
        hour ?? dateTime.Hour,
        minute ?? dateTime.Minute,
        second ?? dateTime.Second
    );
}

public static DateTime SetYear(this DateTime dateTime, int year)
{
    return dateTime.SetPart(year, null, null, null, null, null);
}

public static DateTime SetMonth(this DateTime dateTime, int month)
{
    return dateTime.SetPart(null, month, null, null, null, null);
}

public static DateTime SetDay(this DateTime dateTime, int day)
{
    return dateTime.SetPart(null, null, day, null, null, null);
}

public static DateTime SetHour(this DateTime dateTime, int hour)
{
    return dateTime.SetPart(null, null, null, hour, null, null);
}

public static DateTime SetMinute(this DateTime dateTime, int minute)
{
    return dateTime.SetPart(null, null, null, null, minute, null);
}

public static DateTime SetSecond(this DateTime dateTime, int second)
{
    return dateTime.SetPart(null, null, null, null, null, second);
}

您可以设置单独的DateTime组件,如

var now = DateTime.Now;

now.SetSecond(0);

DateTime出了什么问题。AddSeconds方法,您可以添加或减去秒?

这难道不能解决你的问题吗?

Dateime dt = DateTime.Now;
dt = dt.AddSeconds(10);