There will be 2 buttons of toggle.One will be up and other will be down
Query is if current month is of 30 days then it should display 01 Aug 2017 to 16th Aug 2017 when i toggle up it should show 16th Aug to 30th Aug and similar should work for toggle down.
But if current month is of 31 days then it should display 01 Aug 2017 to 16th Aug 2017 and 16th Aug to 31st Aug and similar should work for toggle down.This should work continous if am trying to toggle up it should display like below
1st Jan to 15th jan then 16th to 30th Jan then 1st Feb to 16th Feb like wise it should go on for toggle up and down.
Code which i tried is below :
public static DateTime GetEndDate(int year, int month)
{
decimal currentmonth = System.DateTime.DaysInMonth(year, month);
decimal value = Math.Ceiling(Convert.ToDecimal(currentmonth / 2));
// DateTime updatedfinaldatevaluestart = new DateTime(year, month, day);
DateTime updatedfinaldatevalueend = new DateTime(year, month, Convert.ToInt32(value));
return updatedfinaldatevalueend;
}
public static DateTime GetStartDate(int year, int month)
{
decimal currentmonth = System.DateTime.DaysInMonth(year, month);
decimal value = Math.Ceiling(Convert.ToDecimal(currentmonth / 2));
// DateTime updatedfinaldatevaluestart = new DateTime(year, month, day);
DateTime updatedfinaldatevalueend = new DateTime(year, month, 01);
return updatedfinaldatevalueend;
}
You don't have to do all these calculations. The first half for all months will always be between the 1st and the 15th (you don't have to calculate 15th. There's no month that has like 45 days). And, the second half will always start from the 16th, and you can get the end date of the month by doing this (startDate is the first day of the month):
var endDate = startDate.AddMonths(1).AddDays(-1);
I suspect there is a better way of doing what you're trying to achieve but there isn't enough information in the question to determine what that is (what is calling these methods, what is happening to the output etc) However, using the method you have posted, this (untested) code may do what you require
The bool parameter should be true when the down button is clicked and false when the up button is clicked
public static DateTime GetEndDate(int year, int month, bool firstHalfOfMonth)
{
if (firstHalfOfMonth == false)
{
return GetStartDate(year, month, false);
}
else
{
return new DateTime(year, month, System.DateTime.DaysInMonth(year, month));
}
}
public static DateTime GetStartDate(int year, int month, bool firstHalfOfMonth)
{
if (firstHalfOfMonth == false)
{
int daysInCurrentMonth = System.DateTime.DaysInMonth(year, month);
int midMonth = Convert.ToInt32(Math.Ceiling((double)daysInCurrentMonth / 2));
return new DateTime(year, month, midMonth);
}
else
{
return new DateTime(year, month, 1);
}
}
Related
I want my new year to start at 14 March. Given any DateTime I want to get the day of year? How can I accomplish this with DateTime?
March 14 is the 73rd day of the year (74th in leap years) in the Gregorian calendar. 292 days remain until the end of the year. Is there a way I can define the new year of a year with DateTime?
int DayOfYear(DateTime date, int yearStartMonth, int yearStartDay)
{
var yearStart = new DateTime(d.Year, yearStartMonth, yearStartDay);
if(yearStart > d)
yearStart = yearStart.AddYears(-1);
return (d - yearStart).Days + 1;
}
try to use:
public static int DayOfYear(DateTime date)
{
var startDate= new DateTime(year:date.Year,month:3,day:14); //14 March
var diffDateDays=(date- startDate).Days;
if (diffDateDays > 0) return diffDateDays;
startDate= new DateTime(year:date.Year-1,month:3,day:14); //14 March of previous year
return (date- startDate).Days;
}
Can anyone please help me, how do I calculate fortnightly (14 days) logic using C#?, for a example 14 days start following sequence order on February
Monday start date 8 Feb (next 22 Feb, 7 March, 21 March etc..)
Thursday start date 11 February (next 25 Feb, 10 March, 24 March etc..)
Friday start date 12 February (next 26 Feb, 11 March, 25 March etc..)
My logic is not working for the 14 days day display, because 15 February will come 14 days add, it’ll display “First14days” date 29 February 2016, it is a wrong.
This is C# logic
Day.Days value are Monday, Thursday, Friday etc..
foreach (var Day in day)
{
Example Day.Days = Monday
Int 14days = (((int)Enum.Parse(typeof(DayOfWeek), Day.Days) - (int)today.DayOfWeek + 14) % 7);
DateTime First14days = today.AddDays(14days);
}
My output should be
Simply add TimeSpan.FromDays(14) to any date to get a fortnight further on
DateTime startDate = DateTime.Now;
TimeSpan fortnight = TimeSpan.FromDays(14);
for (int i = 0; i < 6; i++)
{
startDate += fortnight;
Console.WriteLine($"Date for fortnight {i}: {startDate:D}");
}
If I understand correct your question this code will be working for you.
DateTime time = DateTime.Now;
DateTime anotherTime = DateTime.Now;
var allTimes = new HashSet<DateTime>();
for (int i = 0; i < 6; i++)
{
anotherTime = time.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
// or with your example is possible to like this code.
foreach (var Day in day)
{
anotherTime = Day.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
First create two DataTime objects. then foreach few times, and in for loop statement set anotherTime = time.AddDays(14) after that set time = anotherTime.
//Output:
//Saturday, February 27, 2016
//Saturday, March 12, 2016
//Saturday, March 26, 2016
//Saturday, April 09, 2016
//Saturday, April 23, 2016
//Saturday, May 07, 2016
EDIT:
I create and HashSet where you can save all you DateTime who you make it.
So here's you all-in-one solution:
// determine the date of next given weekday
DateTime date = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
// create a list and add the start date (if you want)
List<DateTime> fortnights = new List<DateTime>() { date };
// add as many "fortnights" as you like (e.g. 5)
for (int i = 0; i < 5; i++)
{
date = date.Add(TimeSpan.FromDays(14));
fortnights.Add(date);
}
// use your list (here: just for printing the list in a console app)
foreach (DateTime d in fortnights)
{
Console.WriteLine(d.ToLongDateString());
}
Method to get the next weekday, from:
https://stackoverflow.com/a/6346190/2019384
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
Suppose my input is March 31, 2015.
How would I be able to get the days of the week that March 31, 2015 is in?
In this case, it should output:
March 29, 2015-April 4, 2015
I found something similar here but it's not quite what I'm looking for as that one takes in the week number while my input is a date itself.
DateTime date = new DateTime(2015, 3, 31);
DateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);
DateTime weekLastDay = weekFirstDay.AddDays(6);
Here is a way to get each value separately from a given DateTime
Week start:
public static DateTime GetWeekStartDate(DateTime value)
{
return value.AddDays(-(int)value.DayOfWeek).Date;
}
Week end:
public static DateTime GetWeekEndDate(DateTime value)
{
return value.AddDays(6 - (int)value.DayOfWeek).Date;
}
DayOfWeek firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DateTime startDate = DateTime.Now;
while (firstDayOfWeek != startDate.DayOfWeek)
{
startDate = startDate.AddDays(-1);
}
DateTime firstDay = startDate.Date;
DateTime lastDay = startDate.AddDays(6);
Assuming I can not change service that returns data, I am left with
var date = "20140231";
var scope = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);
Clearly "20140231" is lazy way of saying end of February. What is the cleanest way to get last date of February with input of "20140231"?
There is 1 constraint - this should work with .net 2.0.
string date = "20140231";
DateTime result;
int year = Convert.ToInt32(date.Substring(0, 4));
int month = Convert.ToInt32(date.Substring(4, 2));
int day = Convert.ToInt32(date.Substring(6, 2));
result = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));
February can have only 28 or 29 days depends on current year is a leap year or not.
It can't have 30 or 31 days in any year. That's why you can't parse your 20140231 string successfully.
You can clearly get the last day of February like;
DateTime lastDayOfFebruary = (new DateTime(2014, 2, 1)).AddMonths(1).AddDays(-1);
If your service always get year as a first 4 character, you can use .Substring() to get year and pass DateTime constructor as a year.
var date = "20140231";
string year = date.Substring(0, 4);
DateTime lastDayOfFebruary = (new DateTime(int.Parse(year), 2, 1)).AddMonths(1).AddDays(-1);
You could create a while, cut the date in pieces, and keep subtracting one from the day part until it is a valid date. This should really be fixed on the entry side though.
Try this:
var date = "20140231";
DateTime scope;
bool dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
while (!dateValid)
{
string yearMonth = date.Substring(0, 4);
int day = Convert.ToInt32(date.Substring(6, 2));
if (day > 1)
{
day--;
}
else
{
break;
}
date = yearMonth + day.ToString().PadLeft(2, '0');
dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
}
I need to return year and week of a given date. Sounds simple. But to be right 2012-01-01 have to return 2011-52, because week 1 in 2012 starts January 2th.
To find the week, I use:
GregorianCalendar calw = new GregorianCalendar(GregorianCalendarTypes.Localized);
return calw.GetWeekOfYear(DateTime.Parse("2012-01-01"), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday).ToString();
this return 52. (correct)
But how do I get the Year?
edit:
With the help from here: http://codebetter.com/petervanooijen/2005/09/26/iso-weeknumbers-of-a-date-a-c-implementation/
This seems to work:
private int weekYear(DateTime fromDate)
{
GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
int week = weekNumber(fromDate);
int month = cal.GetMonth(fromDate);
int year = cal.GetYear(fromDate);
//week starts after 31st december
if (week > 50 && month == 1)
year = year - 1;
//week starts before 1st January
if (week < 5 && month == 12)
year = year + 1;
return year;
}
private int weekNumber(DateTime fromDate)
{
// Get jan 1st of the year
DateTime startOfYear = fromDate.AddDays(-fromDate.Day + 1).AddMonths(-fromDate.Month + 1);
// Get dec 31st of the year
DateTime endOfYear = startOfYear.AddYears(1).AddDays(-1);
// ISO 8601 weeks start with Monday
// The first week of a year includes the first Thursday
// DayOfWeek returns 0 for sunday up to 6 for saterday
int[] iso8601Correction = { 6, 7, 8, 9, 10, 4, 5 };
int nds = fromDate.Subtract(startOfYear).Days + iso8601Correction[(int)startOfYear.DayOfWeek];
int wk = nds / 7;
switch (wk)
{
case 0:
// Return weeknumber of dec 31st of the previous year
return weekNumber(startOfYear.AddDays(-1));
case 53:
// If dec 31st falls before thursday it is week 01 of next year
if (endOfYear.DayOfWeek < DayOfWeek.Thursday)
return 1;
else
return wk;
default: return wk;
}
}
Noda Time handles this for you very easily:
Noda Time v1.x
using System;
using NodaTime;
public class Test
{
static void Main()
{
LocalDate date = new LocalDate(2012, 1, 1);
Console.WriteLine($"WeekYear: {date.WeekYear}"); // 2011
Console.WriteLine($"WeekOfWeekYear: {date.WeekOfWeekYear}"); // 52
}
}
Noda Time v2.x
using System;
using NodaTime;
using NodaTime.Calendars;
public class Test
{
static void Main()
{
LocalDate date = new LocalDate(2012, 1, 1);
IWeekYearRule rule = WeekYearRules.Iso;
Console.WriteLine($"WeekYear: {rule.GetWeekYear(date)}"); // 2011
Console.WriteLine($"WeekOfWeekYear: {rule.GetWeekOfWeekYear(date)}"); // 52
}
}
That's using the ISO calendar system where the week year starts in the first week with at least 4 days in that year. (Like CalendarWeekRule.FirstFourDayWeek.) If you want a different calendar system, specify it in the LocalDate constructor. Week year rules are handled slightly differently between 1.x and 2.x.
EDIT: Note that this gives the right value for both this situation (where the week-year is less than the calendar year) and the situation at the other end of the year, where the week-year can be more than the calendar year. For example, December 31st 2012 is in week 1 of week-year 2013.
That's the beauty of having a library do this for you: its job is to understand this sort of thing. Your code shouldn't have to worry about it. You should just be able to ask for what you want.
You can get the weeknumber according to the CalendarWeekRule in this way:
var d = new DateTime(2012, 01, 01);
System.Globalization.CultureInfo cul = System.Globalization.CultureInfo.CurrentCulture;
var firstDayWeek = cul.Calendar.GetWeekOfYear(
d,
System.Globalization.CalendarWeekRule.FirstDay,
DayOfWeek.Monday);
int weekNum = cul.Calendar.GetWeekOfYear(
d,
System.Globalization.CalendarWeekRule.FirstFourDayWeek,
DayOfWeek.Monday);
int year = weekNum >= 52 && d.Month == 1 ? d.Year - 1 : d.Year;
You probably want to compare CalendarWeekRule.FirstDay with CalendarWeekRule.FirstFourDayWeek. On this way you get the weeknumber and the year (DateTime.Year-1 if they differ).
CultureInfo.Calendar Property
Calendar.GetWeekOfYear Method
CalendarWeekRule Enumeration
That is just an edge case which you will have to add special code for. Get the year from the date string and then if the week = 52 and the month = 1 then subtract one from the year.
I have solving similar problem where the result should be in "YYYYWW" format. I wanted avoid hardcoded dates and using 3rd party libraries.
My test case was date 1.1.2017 which should return week 201652 (Iso YearWeek)
To get week number I have used thread: Get the correct week number of a given date which returns week number without the year.
Finally the correct year I got from Monday(first day of iso week) of required date:
// returns only week number
// from [Get the correct week number of a given date] thread
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
var week = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return week;
}
// returns int YearWeek in format "YYYYWW"
public static int GetIso8601YearWeekOfYear(DateTime time)
{
var delta = (-((time.DayOfWeek - CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7));
var firstDayofWeek = time.AddDays(delta); // takeMonday
var week = GetIso8601WeekOfYear(time);
var yearWeek = (firstDayofWeek.Year * 100) + week;
return yearWeek;
}
In my approach I'm taking advantage of the fact, that GetWeekOfYear() displays a correct ISO-8601 week number for days with the same year as Thursday of the same week. So I look for Thursday that belongs to the same week as a given date, and then call GetWeekOfYear() on it.
I can't do that trick to get a correct year, as there's no iso8601-compliant method for this, so I make a year adjustment if Thursday belongs to a different year than a given date.
The solution is basically a three-liner:
using System.Globalization;
namespace TESTS
{
class Program
{
static void Main(string[] args)
{
//sample dates with correct week numbers in comments:
string[] dats = new string[] {
"2011-12-31","2012-01-01" //1152
,"2012-12-31","2013-01-01" //1301
,"2013-12-31","2014-01-01" //1401
,"2014-12-31","2015-01-01" //1501
,"2015-12-31", "2016-01-01" //1553
};
foreach (string str in dats)
{
Console.WriteLine("{0} {1}", str, GetCalendarWeek(DateTime.Parse(str)));
}
Console.ReadKey();
}
public static int GetCalendarWeek(DateTime dat)
{
CultureInfo cult = System.Globalization.CultureInfo.CurrentCulture;
// thursday of the same week as dat.
// value__ for Sunday is 0, so I need (true, not division remainder %) mod function to have values 0..6 for monday..sunday
// If you don't like casting Days to int, use some other method of getting that thursday
DateTime thursday = dat.AddDays(mod((int)DayOfWeek.Thursday-1,7) - mod((int)dat.DayOfWeek-1,7));
//week number for thursday:
int wk = cult.Calendar.GetWeekOfYear(thursday, cult.DateTimeFormat.CalendarWeekRule, cult.DateTimeFormat.FirstDayOfWeek);
// year adjustment - if thursday is in different year than dat, there'll be -1 or +1:
int yr = dat.AddYears(thursday.Year-dat.Year).Year;
// return in yyww format:
return 100 * (yr%100) + wk;
}
// true mod - helper function (-1%7=-1, I need -1 mod 7 = 6):
public static int mod(int x, int m)
{
return (x % m + m) % m;
}
}