Cómo cambiar la hora en DateTime?


¿Cómo puedo cambiar el tiempo solo en la variable DateTime?

DateTime s = some datetime;

Necesito cambiar solo la parte de tiempo en s.

Author: wonea, 2009-12-07

26 answers

No se puede cambiar un valor DateTime - es inmutable. Sin embargo, puede cambiar la variable para que tenga un nuevo valor. La forma más fácil de hacer eso para cambiar solo la hora es crear un intervalo de tiempo con la hora relevante y usar la fecha y hora.Fecha propiedad:

DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;

s ahora será la misma fecha, pero a las 10.30 am.

Tenga en cuenta que DateTime no tiene en cuenta las transiciones de horario de verano, representando el tiempo gregoriano "ingenuo" en ambas direcciones (vea la sección de Observaciones en el DateTime docs). Las únicas excepciones son .Now y .Today: recuperan la hora actual del sistema que refleja estos eventos a medida que ocurren.

Este es el tipo de cosas que me motivaron a comenzar el proyecto Noda Time, que ahora está listo para la producción. Su tipo ZonedDateTime se hace "consciente" vinculándolo a una entrada de base de datos tz .

 494
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-08 12:59:47

Muy bien Estoy buceando con mi sugerencia, un método de extensión:

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);
}

Luego llama:

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

Es importante tener en cuenta que esta extensión devuelve un nuevo objeto de fecha, por lo que no puede hacer esto:

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

Pero puedes hacer esto:

DateTime myDate = DateTime.Now;
myDate = myDate.ChangeTime(10,10,10,0);
 85
Author: joshcomley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 11:12:36
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);

De esta manera conservas tu fecha, mientras insertas una nueva parte de horas, minutos y segundos a tu gusto.

 59
Author: Webleeuw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-03 11:34:57

Un revestimiento

var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));

Traería de vuelta la fecha de hoy con una hora de 4:30:00, reemplazaría DateTime.Ahora con cualquier objeto de fecha

 24
Author: Carl Woodhouse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-23 10:18:11

DateTime es un tipo inmutable, por lo que no puede cambiarlo.

Sin embargo, puede crear una nueva instancia DateTime basada en la instancia anterior. En su caso, parece que necesita la propiedad Date, y luego puede agregar un intervalo de tiempo que represente la hora del día.

Algo como esto:

var newDt = s.Date + TimeSpan.FromHours(2);
 19
Author: Mark Seemann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 10:51:21

Si ya tiene el tiempo almacenado en otro objeto DateTime puede usar el método Add.

DateTime dateToUse = DateTime.Now();
DateTime timeToUse = new DateTime(2012, 2, 4, 10, 15, 30); //10:15:30 AM

DateTime dateWithRightTime = dateToUse.Date.Add(timeToUse.TimeOfDay);

La propiedad TimeOfDay es un objeto TimeSpan y se puede pasar al método Add. Y como usamos la propiedad Date de la variable dateToUse obtenemos solo la fecha y agregamos el lapso de tiempo.

 13
Author: ShaneA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-06 22:46:55

Sucedió en este post, ya que estaba buscando la misma funcionalidad que esto podría hacer lo que el chico quería. Tome la fecha original y reemplace la parte de tiempo

DateTime dayOpen = DateTime.Parse(processDay.ToShortDateString() + " 05:00 AM");
 8
Author: BlackLarry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-30 03:20:15
DateTime ts = DateTime.Now;
ts = new DateTime ( ts.Year, ts.Month, ts.Day, 0, 0, 0 ) ;
Console.WriteLine ( "Today = " + ts.ToString("M/dd/yy HH:mm:ss") ) ;

Ejecutado: Hoy = 9/04/15 00:00:00

 8
Author: philip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 06:34:17

La solución más simple :

DateTime s = //some Datetime that you want to change time for 8:36:44 ;
s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44);

Y si necesita un Formato de Fecha y Hora específico:

s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44).ToString("yyyy-MM-dd h:mm:ss");
 6
Author: Mr Rubix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-28 19:30:20

Si tienes una fecha y hora como 2014/02/05 18: 19: 51 y quieres solo 2014/02/05, puedes hacer eso:

_yourDateTime = new DateTime(_yourDateTime.Year, _yourDateTime.Month, _yourDateTime.Day)
 3
Author: Cássio Alan Garcia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 20:23:36

Añadiendo .Fecha a su fecha establece a medianoche (00:00).

MyDate.Date

Nota El SQL equivavalente es CONVERT(DATETIME, CONVERT(DATE, @MyDate))

Lo que hace que este método sea tan bueno es que es rápido de escribir y fácil de leer. Una ventaja es que no hay conversión de cadenas.

Es decir, para fijar la fecha de hoy a las 23:30, use:

DateTime.Now.Date.AddHours(23).AddMinutes(30)

Por supuesto, puede reemplazar DateTime.Ahora o MyDate con cualquier fecha de su elección.

 3
Author: Knickerless-Noggins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-17 07:11:14
int year = 2012;
int month = 12;
int day = 24;
int hour = 0;
int min = 0;
int second = 23;
DateTime dt = new DateTime(year, month, day, hour, min, second);
 2
Author: Sagar Rawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-20 06:25:24

Use Date.Add y agregue un New TimeSpan con la nueva hora que desea agregar

DateTime dt = DateTime.Now
dt.Date.Add(new TimeSpan(12,15,00))
 2
Author: Yonatan Tuchinsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-17 18:52:36

Aquí hay un método que puedes usar para hacerlo por ti, úsalo así

DateTime newDataTime = ChangeDateTimePart(oldDateTime, DateTimePart.Seconds, 0);

Aquí está el método, probablemente hay una mejor manera, pero acabo de azotado esto:

public enum DateTimePart { Years, Months, Days, Hours, Minutes, Seconds };
public DateTime ChangeDateTimePart(DateTime dt, DateTimePart part, int newValue)
{
    return new DateTime(
        part == DateTimePart.Years ? newValue : dt.Year,
        part == DateTimePart.Months ? newValue : dt.Month,
        part == DateTimePart.Days ? newValue : dt.Day,
        part == DateTimePart.Hours ? newValue : dt.Hour,
        part == DateTimePart.Minutes ? newValue : dt.Minute,
        part == DateTimePart.Seconds ? newValue : dt.Second
        );
}
 1
Author: naspinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 11:13:04

Acabo de encontrar este post porque tuve un problema similar por el que quería establecer la hora para un objeto Entity Framework en MVC que obtiene la fecha de una vista (datepicker), por lo que el componente time es 00:00:00, pero necesito que sea la hora actual. Basado en las respuestas en este post se me ocurrió:

myEntity.FromDate += DateTime.Now.TimeOfDay;
 1
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-04 12:10:57
//The fastest way to copy time            

DateTime justDate = new DateTime(2011, 1, 1); // 1/1/2011 12:00:00AM the date you will be adding time to, time ticks = 0
DateTime timeSource = new DateTime(1999, 2, 4, 10, 15, 30); // 2/4/1999 10:15:30AM - time tick = x

justDate = new DateTime(justDate.Date.Ticks + timeSource.TimeOfDay.Ticks);

Console.WriteLine(justDate); // 1/1/2011 10:15:30AM
Console.Read();
 1
Author: Pawel Cioch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-29 11:42:47

¿Qué tiene de malo DateTime?Método AddSeconds donde puede agregar o restar segundos?

 0
Author: Chris Richner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 10:50:29

Cuando construya su objeto DateTime, use un constructor que le permita especificar el tiempo:

var myDateTime = new DateTime(2000, 01, 01, 13, 37, 42);  // 2000-01-01 13:37:42

Si ya tiene un objeto DateTime y desea cambiar la hora, puede agregar minutos, horas o segundos a su DateTime utilizando métodos simples:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime = myDateTime.AddHours(13);                     // 2000-01-01 13:00:00
myDateTime = myDateTime.AddMinutes(37);                   // 2000-01-01 13:37:00
myDateTime = myDateTime.AddSecounds(42);                  // 2000-01-01 13:37:42

Observe cómo tenemos que "guardar" el resultado de cada llamada de método a la variable myDateTime. Esto se debe a que DateTime es inmutable, y sus métodos simplemente crean nuevas instancias con las horas/minutos/segundos adicionales añadir.

Si necesita agregar tanto horas como minutos (y / o segundos) y al mismo tiempo, puede simplificar el código agregando un TimeSpan al DateTime original en su lugar:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42);                   // 2000-01-01 13:37:42

Si desea establecer horas/minutos/segundos absolutos, en lugar de agregar a los valores existentes, puede usar el constructor DateTime mencionado anteriormente, y reutilizar los valores para año/mes/día de anteriores:

myDateTime = new DateTime(myDateTime.Year, myDateTime.Month, myDateTime.Day,
                          20, 33, 19)                     // 2000-01-01 20:33:19
 0
Author: Jørn Schou-Rode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 11:11:22

¿Eso no soluciona tus problemas??

Dateime dt = DateTime.Now;
dt = dt.AddSeconds(10);
 0
Author: Naveed Butt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-10 10:10:46

Prefiero esto:

DateTime s = //get some datetime;
s = new DateTime(s.Year, s.Month,s.Day,s.Hour,s.Minute,0);
 0
Author: andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-28 23:16:57
 Using an extencion to DateTime:  

        public enum eTimeFragment
        {
            hours,
            minutes,
            seconds,
            milliseconds
        }
        public static DateTime ClearTimeFrom(this DateTime dateToClear, eTimeFragment etf)
        {
            DateTime dtRet = dateToClear;
            switch (etf)
            {
                case eTimeFragment.hours:
                    dtRet = dateToClear.Date;
                    break;
                case eTimeFragment.minutes:
                    dtRet = dateToClear.AddMinutes(dateToClear.Minute * -1);
                    dtRet = dtRet.ClearTimeFrom(eTimeFragment.seconds);
                    break;
                case eTimeFragment.seconds:
                    dtRet = dateToClear.AddSeconds(dateToClear.Second * -1);
                    dtRet = dtRet.ClearTimeFrom(eTimeFragment.milliseconds);
                    break;
                case eTimeFragment.milliseconds:
                    dtRet = dateToClear.AddMilliseconds(dateToClear.Millisecond * -1);
                    break;
            }
            return dtRet;

        }

Use así:

Consola.WriteLine (DateTime.Ahora.ClearTimeFrom (eTimeFragment.horas))

Esto tiene que volver: 2016-06-06 00:00:00.000

 0
Author: Ricardo Figueiredo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-07 14:55:07

Dado que DateTime es inmutable, se debe crear una nueva instancia cuando se necesita cambiar un componente date. Desafortunadamente, no hay una funcionalidad incorporada para establecer componentes individuales de una instancia DateTime.

Utilizando los siguientes métodos de extensión

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);
}

Puede establecer componentes individuales DateTime como

var now = DateTime.Now;

now.SetSecond(0);
 0
Author: solidsparrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-05 10:41:38
  DateTime s;
//s = datevalue
                s = s.AddMilliseconds(10);
                s = s.AddMinutes(10);
                s = s.AddSeconds(10);
                s = s.AddHours(10);

Puede agregar valores +ve/-ve en el parámetro.

s.Add(new TimeSpan(1, 1, 1));
 -1
Author: Saar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 11:17:00

La mejor solución es:

currdate.AddMilliseconds(currdate.Millisecond * -1).AddSeconds(currdate.Second * -1).AddMinutes(currdate.Minute * -1).AddHours(currdate.Hour * -1);
 -1
Author: Mahesh Alwani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-28 23:27:32

Prueba este

var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;
 -1
Author: vicky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-27 05:23:31

Aquí hay una forma de gueto, pero funciona:)

DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));
 -5
Author: naspinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-07 10:55:00