Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the year in a DateTime object

Tags:

c#

datetime

How would I go about changing only the year in a datetime object?

I need to call a number of dates from excel, and if the dates I call are before todays date, set the year to 2099.

e.g. date that is called: 15/11/2010 needs to be set to 15/11/2099

Is this doable? or would it be best to change the whole date?

like image 265
Joshua Cameron-Mackintosh Avatar asked Jan 23 '17 11:01

Joshua Cameron-Mackintosh


People also ask

How do I change datetime to year?

DateTime is immutable type. You cannot change year or any other part of it. You should create new DateTime instance with new year.

How do I add one year to a datetime object?

In pandas, a string is converted to a datetime object using the pd. to_datetime() method. pd. DateOffset() method is used to add years to the created pandas object.

How do I format a datetime object in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


2 Answers

You just need to create a new DateTime since DateTime is an immutable struct:

DateTime newDt = new DateTime(2099, dt.Month, dt.Day);

If you want to handle the leapyear issue(source date is in leapyear but target year not), you could use following extension method:

public static DateTime ChangeYear(this DateTime dt, int newYear)
{
    return dt.AddYears(newYear - dt.Year);
}

This will retain even the Ticks and the Kind, so it's better than using the DateTime constructor. It will return 02/28/2099 if the orginal DateTime was 02/29/2016(leap year).

You can use it for example in this way:

DateTime dt = new DateTime(2016, 2, 29);
DateTime newDt = dt.ChangeYear(2099); 
like image 108
Tim Schmelter Avatar answered Nov 17 '22 01:11

Tim Schmelter


DateTime is immutable type. You cannot change year or any other part of it. You should create new DateTime instance with new year. There is no other option.

var date1 = DateTime.Now;
var date2 = new DateTime(2099, date1.Month, date1.Day);

Though you can write an extension if you need to do it often:

public static DateTime JumpToYear(this DateTime date, int year)
{
    // you can also provide Hour, Minute, Second and Millisecond
    return new DateTime(year, date.Month, date.Day);
}

Usage:

var date2 = date1.JumpToYear(2099);

Note: February 29 date can become invalid when you change year.

like image 21
Sergey Berezovskiy Avatar answered Nov 17 '22 01:11

Sergey Berezovskiy