2014年7月13日 星期日

[RESOLVED] How to find day in current date to previous year of the same date


How to find day in  current date   to    previous year of the same date 



You can try with the below code


  //Get Current Date
DateTime now = DateTime.Now.Date;

//Get LastYear Day details for current date
DateTime sameDayLastYear = new DateTime(now.Year - 1, now.Month, now.Day);

//Get the Date here
string datevalue = sameDayLastYear.Date.ToString();

//Get the Day here
string dayvalue = sameDayLastYear.Day.ToString();

//Get Day name here
string Dayofweekvalue = sameDayLastYear.DayOfWeek.ToString();

//Get the Day of Year here
string DayofYearValue = sameDayLastYear.DayOfYear.ToString();


Source URL




You would just need to create another DateTime object that used the same month and date and check the appropriate

DayOfWeek property
:


// Get Todays' Date
var today = DateTime.Today;

// Approach One : Use the AddYears method to get the day for the previous year
var lastYear = today.AddYears(-1);

// Approach Two : Create a New Date Object using the same month and Day from today except with a lower year
var lastYear = new DateTime(today.Year - 1, today.Month, today.Day);

// After you have last year's value, simply use the DayOfWeek property to access what day it was
var dayLastYear = lastYear.DayOfWeek;

which could be simplified to the following :


// Get the DayOfTheWeek for the same day last year
var dayOfWeek = DateTime.Today.AddYears(-1).DayOfWeek;

or :


// Get the DayOfTheWeek for the same day last year
var dayOfWeek = new DateTime(DateTime.Today.Year -1, DateTime.Today.Month, DateTime.Today.Day).DayOfWeek;


This really depends on exactly what you need. If you just need the same actual Date just in the previous year, these should work. If you needed something like the number of days that have elapsed, then you would likely need to take a different approach and
use the
DayOfYear property
for the previous year.


沒有留言:

張貼留言