<script Language="c#" runat="server">
void Page_Load()
{
int currentYear = DateTime.Now.Year();
if (currentYear % 400 == 0) {
Message2.Text = ("This is a leap year");
}
else {
Message2.Text = ("This is not a leap year");
}
}
Currently I am getting a RunTime error. My goal is to test whether or not the current year, using DateTime.Now.Year() is a leap year or not. I think the issue is that I am not properly converting year to int? Please advise.
You can just use DateTime.IsLeapYear():
if (DateTime.IsLeapYear(year))
{
//do stuff
}
For those that come here for the rules:
According to wikipedia, these extra days occur in each year
which is an integer multiple of 4.
years that are evenly divisible by 100 are not leap years unless evenly divisible by 400.
So this results in this function:
// PRE: no year < 1 or > 9999
// POST: true if year is a leap year, or false if not.
public static bool IsLeapYear(int year)
{
if (year < 1 || year > 9999)
{
throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Year"));
}
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
And now I'm wondering what should happen if I use minus-years for BC - actually, the question is which calendar does even apply, especially prior to 1753 (for Britain) ? ;)
I use C# and this code for leap years.
cheers
if ((jahr % 4 == 0 && jahr % 400 == 0) || (jahr % 4 == 0 && !(jahr % 100 == 0)))
{
Console.WriteLine(jahr + " ist ein Schaltjahr");
}
else
Console.WriteLine(jahr + " ist kein Schaltjahr");
static int GeveDays()
{
int days;
if ((DateTime.Now).Year / 4 != 1 || (DateTime.Now).Year / 400 != 1) {
Console.WriteLine("it is a common year");
days = 365;
return days;
}
else if ((DateTime.Now).Year / 100 != 1) {
Console.WriteLine("it is a leap year");
days = 366;
return days;
}
else {
Console.WriteLine("it is a leap year");
days = 366;
return days;
}
}
int x= int.Parse(Console.ReadLine());
if((x%400==0)||(x%100==0)||(x%4==0))
{
Console.WriteLine(" \n\n\n The year is a leap year ...!");
}
else
{
Console.WriteLine("\n\n\n The year is not a leap year");
}
Related
I've been trying to convert a given date to ticks using the following formula and since I've just begun writing this function I do not yet consider the month and day values :
public static long DateToTicks(int year, int month, int day) {
var leapYears = (year - 1) / 4;
var result = ((year - 1) * 365 * OneDay.Ticks) + (leapYears * OneDay.Ticks);
return result;
}
The OneDay.Ticks is a constant here whose value is 3600 * 24 * 1000 * 10000.
The problem I have faced is that, when I calculate ticks from day zero (i.e. 0001-01-01, 0002-01-01) it works fine until I reach year 101 where I get an additional day! I compare my result against the value returned by the DateTime struct in .Net Core. For example:
var myResult = DateToTicks(100, 01, 01);
var dateTimeResult = new DateTime(100,01,01).Ticks;
Until this date, myResult == dateTimeResult is always true, but when I enter the next century I see that the result returned by DateTime struct is one day behind, and as I enter another century this value doubles.
However, I know that in 101 years, there are 25 leap years which means that I have to multiply 75 years by 365 and the rest by 366 and then add them together, and I cannot understand why my result is different from dot net's DateTime result.
What's the problem with my approach? Given that month and day would be not important (always set to 01).
since you dont seem to want to look at the c# code. I looked there for you - took me 1 minute
private static long DateToTicks(int year, int month, int day) {
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) {
int[] days = IsLeapYear(year)? DaysToMonth366: DaysToMonth365;
if (day >= 1 && day <= days[month] - days[month - 1]) {
int y = year - 1;
int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return n * TicksPerDay;
}
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
and
public static bool IsLeapYear(int year) {
if (year < 1 || year > 9999) {
throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Year"));
}
Contract.EndContractBlock();
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
here is the direct link
https://referencesource.microsoft.com/#mscorlib/system/datetime.cs,891f8af5025ab2f3
Change your logic for leap year calculation to this and it works well:
var leapYears = ((year - 1) / 4) - (year / 400 > 0 ? ((year) / 100) - (((year) / 400)) : ((year - 1) / 100)) + (year % 100 == 0 && year % 400 != 0 ? 1 : 0) + (year == 100 || year == 200 || year == 300 ? -1 : 0);
A simple divide by 4 is not the correct way to determine a leap year.
Here is a way to test for a leap year:
The year can be evenly divided by 4;
If the year can be evenly divided by 100, it is NOT a leap year, unless;
The year is also evenly divisible by 400. Then it is a leap year.
So, 1900 is not a leap year, but 2000 is a leap year.
The system I'm working on is built and configured in such a way, where users cannot choose leap years when setting up a recurring payment. This results in all the date-math behind the scenes having to ignore leap years. (I didn't choose this, but this is how it was written)
I have to write a method that takes in a DateTime value, and adds days to the date, ignoring leap years, which essentially means ignoring Feb 29th and pretending it doesn't exist.
For example, If I'm adding 365 days to 1/1/2016, that should result in 1/1/2017, not 12/31/2016.
I'm using .NET, so I can make use of DateTime.IsLeapYear, and other helper methods.
This is a work in progress, and here is what I have so far. I started taking a simpler route, and I'm now realizing that it's going to require a more complex algorithm.
public static DateTime AddDaysToDateWithLeapYearConsideration(DateTime date, int daysToAdd)
{
// Nothing to do
if (daysToAdd == 0)
{
return date;
}
// NOTE: This is an invalid approach; using DateTime.AddDays will take leap years into account
DateTime dateWithAddedDays = date.AddDays(daysToAdd);
const int FEB_28_DAY_OF_YEAR = 59;
int daysToSubtractForLeapYearConsideration = 0;
// The year is a leap year, which is under the feb 28 day threshold, and we're adding enough days to push it over the feb 28 day threshold
// This will result in .NET taking into account the feb 29th (the leap year day), but we have to subtract that leap year day since the system doesn't take feb 29th into account
if (DateTime.IsLeapYear(date.Year) && date.DayOfYear < FEB_28_DAY_OF_YEAR && (date.DayOfYear + daysToAdd > FEB_28_DAY_OF_YEAR))
{
daysToSubtractForLeapYearConsideration++;
}
// The resulting date (after the days are added or subtracted) is a leap year, whose day is past the feburary 28 day threshold, and it's not the same year as the date (i.e. it spans across "n" years)
if (DateTime.IsLeapYear(dateWithAddedDays.Year) && dateWithAddedDays.DayOfYear > FEB_28_DAY_OF_YEAR && dateWithAddedDays.Year != date.Year)
{
daysToSubtractForLeapYearConsideration++;
}
// We determined if the original date should be leap year considered, as well as the resulting date/year with the days added. Now see if there are any years in between
// that we should consider
bool isThereAYearRangeThatWeNeedToEvaluateLeapYearsFor = Math.Abs(date.Year - dateWithAddedDays.Year) > 0;
if (isThereAYearRangeThatWeNeedToEvaluateLeapYearsFor)
{
for (int leapYearEvalIndex = Math.Min(date.Year, dateWithAddedDays.Year); leapYearEvalIndex <= Math.Max(date.Year, dateWithAddedDays.Year); leapYearEvalIndex++)
{
bool isYearPartOfTheYearsThatWeveAlreadyChecked = leapYearEvalIndex == date.Year || leapYearEvalIndex == dateWithAddedDays.Year;
if (!isYearPartOfTheYearsThatWeveAlreadyChecked && DateTime.IsLeapYear(leapYearEvalIndex))
{
daysToSubtractForLeapYearConsideration++;
}
}
}
DateTime dateResult = date.AddDays(daysToAdd - daysToSubtractForLeapYearConsideration);
// The system does not allow 2/29 days, hence all this crazy date math
if (dateResult.Month == 2 && dateResult.Day == 29)
{
dateResult = dateResult.AddDays(1);
}
return dateResult;
}
The logic has to take into account negative numbers as well (i.e. subtracting), which the above code fails on.
The above code by no means works, but I wanted to demonstrate that I'm trying to tackle the problem, and not simply asking without having tried anything.
Edit
I've come up with an algorithm pretty close to David's approach. (I wrote it, and then came back to StackOverflow to check responses).
public static DateTime AddDaysToDateWithLeapYearConsideration(DateTime date, int daysToAdd)
{
// Nothing to do
if (daysToAdd == 0)
{
return date;
}
DateTime dateResult = date;
// Are we adding or subtracting
bool areWeAddingDays = daysToAdd > 0;
int daysToAccountForInRegardToLeapYearDates = 0,
absDaysToAdd = Math.Abs(daysToAdd);
for (int i = 1; i <= absDaysToAdd; i++)
{
dateResult = dateResult.AddDays(areWeAddingDays ? 1 : -1);
if (dateResult.Month == 2 && dateResult.Day == 29)
{
daysToAccountForInRegardToLeapYearDates++;
}
}
dateResult = dateResult.AddDays(areWeAddingDays ? daysToAccountForInRegardToLeapYearDates : -daysToAccountForInRegardToLeapYearDates);
return dateResult;
}
Here is an extension method that works. Will also work if you're adding or subtracting enough days to span multiple leap years.
public static DateTime AddDaysWithoutLeapYear(this DateTime input, int days)
{
var output = input;
if (days != 0)
{
var increment = days > 0 ? 1 : -1; //this will be used to increment or decrement the date.
var daysAbs = Math.Abs(days); //get the absolute value of days to add
var daysAdded = 0; // save the number of days added here
while (daysAdded < daysAbs)
{
output = output.AddDays(increment);
if (!(output.Month == 2 && output.Day == 29)) //don't increment the days added if it is a leap year day
{
daysAdded++;
}
}
}
return output;
}
Might need some more testing, but without using the DateTime Add... functions or too much looping, a possible custom implementation:
public static DateTime AddDaysToDateWithLeapYearConsideration(DateTime date, int daysToAdd)
{
int year = date.Year + daysToAdd / 365, month = date.Month - 1, dir = Math.Sign(daysToAdd);
daysToAdd = (daysToAdd % 365) + date.Day;
int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
while(daysToAdd > months[month] || daysToAdd < 0){
if(dir ==1) daysToAdd -= months[month];
month += dir;
if(month == 12 || month == -1){
year += dir;
month = dir == -1 ? 11 : 0;
}
if(dir ==-1) daysToAdd += months[month]; //for reverse direction, add previous month
}
return new DateTime(year, ++month,daysToAdd);
}
I was looking for a method that display dates like in stackoverflow
something like :
1 hour ago
2 minutes ago
Just now
Etc...
Here a method to do so :
static string GetPrettyDate(DateTime d)
{
// 1.
// Get time span elapsed since the date.
TimeSpan s = DateTime.Now.Subtract(d);
// 2.
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// 3.
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// 4.
// Don't allow out of range values.
if (dayDiff < 0 || dayDiff >= 31)
{
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0)
{
// A.
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// 6.
// Handle previous days.
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} weeks ago",
Math.Ceiling((double)dayDiff / 7));
}
return null;
}
Source : http://www.dotnetperls.com/pretty-date
I was using this method in code behind in c#.net. I would pass the date fetched from the database into this method's parameter and then get date written in informal format. Now what is happening is that I have to implement the same thing in my jquery code and
I need to use this function there. In my JavaScript file I am getting the date as a string. Now the problem is that I have no clue how to convert theat string into a Date! Then hpw should I use that date and pass it on to this function? Then do conversions for example this .....(int)s.TotalSeconds;
Give me some ideas how I can implement what I want. I am new to JQuery and stuff.
static string GetInformalDate(DateTime d)
{
// 1.
// Get time span elapsed since the date.
TimeSpan s = DateTime.Now.Subtract(d);
// 2.
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// 3.
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// 4.
// Don't allow out of range values.
if (dayDiff < 0)
{
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0)
{
// A.
// Less than one minute ago.
if (secDiff < 60)
{
return "Just Now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// 6.
// Handle previous days, months and years.
if (dayDiff == 1)
{
return "Yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} week(s) ago",
Math.Ceiling((double)dayDiff / 7));
}
if (dayDiff < 365)
{
return string.Format("{0} month(s) ago", Math.Ceiling((double)dayDiff / 31));
}
else
{
return string.Format("{0} year(s) ago", Math.Ceiling((double)dayDiff / 365));
}
return null;
}
# IAbstractDownvoteFactory :: I am in that chat room. can you please come if your still here..waiting..need help bad :(
Is there anyone else who can help me out please??
Example
function GetUnformalDate(d) {
// 1.
// Get time span elapsed since the date.
var s = new Date().getTime() - d.getTime();
// 2.
// Get total number of days elapsed.
var dayDiff = (s / 86400000) | 0;
// 3.
// Get total number of seconds elapsed.
var secDiff = s / (1000);
// 4.
// Don't allow out of range values.
if (dayDiff < 0) {
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0) {
// A.
// Less than one minute ago.
if (secDiff < 60) {
return "Just Now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120) {
return "1 minute ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600) {
return Math.floor(secDiff / 60) + " minutes ago";
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200) {
return "1 hour ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400) {
return Math.floor(secDiff / 3600) + " hours ago";
}
}
// 6.
// Handle previous days, months and years.
if (dayDiff == 1) {
return "Yesterday";
}
if (dayDiff < 7) {
return dayDiff + " days ago";
}
if (dayDiff < 31) {
return Math.ceil(dayDiff / 7) + " week(s) ago";
}
if (dayDiff < 365) {
return Math.ceil(dayDiff / 31) + " month(s) ago";
}
else {
return Math.ceil(dayDiff / 365) + " year(s) ago";
}
return null;
}
As fpr your date string, we have to parse that:
var digits = "29-07-2011 12:51:33".match(/\d+/g);
var date = new Date(digits[2], digits[1], digits[0], digits[3], digits[4], digits[5])
The following method retuns null if the date is like few months back or year old. If I want to display date as "2 month(s) ago" or like "1 year(s) ago". How should I modify the following method?
// 1.
// Get time span elapsed since the date.
TimeSpan s = DateTime.Now.Subtract(d);
// 2.
// Get total number of days elapsed.
int dayDiff = (int)s.TotalDays;
// 3.
// Get total number of seconds elapsed.
int secDiff = (int)s.TotalSeconds;
// 4.
// Don't allow out of range values.
if (dayDiff < 0 || dayDiff >= 31)
{
return null;
}
// 5.
// Handle same-day times.
if (dayDiff == 0)
{
// A.
// Less than one minute ago.
if (secDiff < 60)
{
return "just now";
}
// B.
// Less than 2 minutes ago.
if (secDiff < 120)
{
return "1 minute ago";
}
// C.
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format("{0} minutes ago",
Math.Floor((double)secDiff / 60));
}
// D.
// Less than 2 hours ago.
if (secDiff < 7200)
{
return "1 hour ago";
}
// E.
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format("{0} hours ago",
Math.Floor((double)secDiff / 3600));
}
}
// 6.
// Handle previous days.
if (dayDiff == 1)
{
return "yesterday";
}
if (dayDiff < 7)
{
return string.Format("{0} days ago",
dayDiff);
}
if (dayDiff < 31)
{
return string.Format("{0} weeks ago",
Math.Ceiling((double)dayDiff / 7));
}
return null;
}
After the if block: if (dayDiff < 31) { ... } insert the following code:
if (dayDiff < 365)
{
return string.Format("{0} month(s) ago", Math.Ceiling((double)dayDiff / 31));
}
else
{
return string.Format("{0} year(s) ago", Math.Ceiling((double)dayDiff / 365));
}
you can directly compare TimeSpans like:
TimeSpan s = DateTime.Now.Subtract(d);
if (s < TimeSpan.FromDays(1))
{
// ...
}
else if (s < TimeSpan.FromMonth(1))
{
// ...
}
// ...
just combine this the way you want exactly (sorry but that I cannot really parse from your question)
I think you might like:
TimeSpan s = DateTime.Now.Subtract(d);
if (s < TimeSpan.FromDays(1))
{
return string.Format("{0:0} hour(s) ago", s.TotalHours);
}
else if (s < TimeSpan.FromDays(7))
{
return string.Format("{0:0} day(s) ago", s.TotalDays);
}
// ...