473,756 Members | 6,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

More elegant way to get "Friday of last week"?

Hi all,

This is how I'm currently getting Friday of last week. It strikes me as
cumbersome. Is there a slicker/more elegant way?

Thanks for any ideas,

cdj

private string prevFridayStrin g(DateTime day)
{
DateTime rv;
int offset = 0;

switch (day.DayOfWeek)
{
case DayOfWeek.Sunda y:
offset = 5;
break;
case DayOfWeek.Monda y:
offset = 4;
break;
case DayOfWeek.Tuesd ay:
offset = 3;
break;
case DayOfWeek.Wedne sday:
offset = 2;
break;
case DayOfWeek.Thurs day:
offset = 1;
break;
case DayOfWeek.Frida y:
offset = 0;
break;
case DayOfWeek.Satur day:
offset = -1;
break;
}

rv = day.AddDays(-7 + offset);
return rv.ToShortDateS tring();
}

Nov 16 '06 #1
10 32827
sherifffruitfly wrote:
This is how I'm currently getting Friday of last week. It strikes me as
cumbersome. Is there a slicker/more elegant way?
Something like:

DateTime dt = DateTime.Now;
while(dt.DayOfW eek != DayOfWeek.frida y) dt = dt.AddDays(-1);

[untested - please check]

Arne
Nov 16 '06 #2

Arne Vajhøj wrote:
>
DateTime dt = DateTime.Now;
while(dt.DayOfW eek != DayOfWeek.frida y) dt = dt.AddDays(-1);
Nice. The idea is perfectly clear - thanks!

cdj

Nov 16 '06 #3
sherifffruitfly wrote:
Arne Vajhøj wrote:
>DateTime dt = DateTime.Now;
while(dt.DayOf Week != DayOfWeek.frida y) dt = dt.AddDays(-1);

Nice. The idea is perfectly clear - thanks!
If you want to go 7 days back if today is Friday then you will need:

DateTime dt = DateTime.Now.Ad dDays(-1);

You should also note that it is not optimized for speed.

But any maintenance programmer reading the code will understand
the "algorithm" .

Arne
Nov 16 '06 #4
You can achieve this quite easily using recurssion

public partial class Form1 : Form
{

private DateTime lastFriday;

public Form1()
{
InitializeCompo nent();
}

private void monthCalendar1_ DateSelected(ob ject sender,
DateRangeEventA rgs e)
{
selectedText.Te xt = e.Start.ToShort DateString();
GetLastFriday(e .Start);
lastFridayText. Text = lastFriday.ToSh ortDateString() ;
}

private void GetLastFriday(D ateTime dateTime)
{
dateTime = dateTime.Subtra ct(new TimeSpan(1,0,0, 0));
if (dateTime.DayOf Week == DayOfWeek.Frida y)
{
lastFriday = dateTime;
return;
}
else
GetLastFriday(d ateTime);
}
}

Remember to add a check so your method doesnt execute more than 7 times
(days in a week) or you could get a stack overflow if things go wrong

On Nov 16, 1:14 pm, "sherifffruitfl y" <sherifffruit.. .@gmail.com>
wrote:
Hi all,

This is how I'm currently getting Friday of last week. It strikes me as
cumbersome. Is there a slicker/more elegant way?

Thanks for any ideas,

cdj

private string prevFridayStrin g(DateTime day)
{
DateTime rv;
int offset = 0;

switch (day.DayOfWeek)
{
case DayOfWeek.Sunda y:
offset = 5;
break;
case DayOfWeek.Monda y:
offset = 4;
break;
case DayOfWeek.Tuesd ay:
offset = 3;
break;
case DayOfWeek.Wedne sday:
offset = 2;
break;
case DayOfWeek.Thurs day:
offset = 1;
break;
case DayOfWeek.Frida y:
offset = 0;
break;
case DayOfWeek.Satur day:
offset = -1;
break;
}

rv = day.AddDays(-7 + offset);
return rv.ToShortDateS tring();
}
Nov 16 '06 #5
<ni***********@ iinet.net.auwro te in message
news:11******** **************@ h54g2000cwb.goo glegroups.com.. .
You can achieve this quite easily using recurssion
Yes, you can. And it's a classic example of a problem that *shouldn't* be
done using recursion.

Don't use recursion when a simple loop will suffice. Recursion is great if
you have a need to unwind all of your state. It's a complete waste of
coding effort, stack space, and execution time when one never needs to
actually revisit previous results, as is the case here.

Pete
Nov 16 '06 #6
Did everyone miss?:

private string prevFridayStrin g(DateTime day)
{
return day.AddDays(-((int)day.DayOf Week) + 2)).ToShortDate String();
}

Remember that the underlying values for the DayOfWeek enumeration are int's
with Sunday being 0 and Saturday being 6.

Therfore is is simply a matter of subtracting the value of (day.DayOfWeek
plus 2).
"sherifffruitfl y" <sh************ *@gmail.comwrot e in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
Hi all,

This is how I'm currently getting Friday of last week. It strikes me as
cumbersome. Is there a slicker/more elegant way?

Thanks for any ideas,

cdj

private string prevFridayStrin g(DateTime day)
{
DateTime rv;
int offset = 0;

switch (day.DayOfWeek)
{
case DayOfWeek.Sunda y:
offset = 5;
break;
case DayOfWeek.Monda y:
offset = 4;
break;
case DayOfWeek.Tuesd ay:
offset = 3;
break;
case DayOfWeek.Wedne sday:
offset = 2;
break;
case DayOfWeek.Thurs day:
offset = 1;
break;
case DayOfWeek.Frida y:
offset = 0;
break;
case DayOfWeek.Satur day:
offset = -1;
break;
}

rv = day.AddDays(-7 + offset);
return rv.ToShortDateS tring();
}

Nov 16 '06 #7
PS

<ni***********@ iinet.net.auwro te in message
news:11******** **************@ h54g2000cwb.goo glegroups.com.. .
You can achieve this quite easily using recurssion

public partial class Form1 : Form
{

private DateTime lastFriday;

public Form1()
{
InitializeCompo nent();
}

private void monthCalendar1_ DateSelected(ob ject sender,
DateRangeEventA rgs e)
{
selectedText.Te xt = e.Start.ToShort DateString();
GetLastFriday(e .Start);
lastFridayText. Text = lastFriday.ToSh ortDateString() ;
}

private void GetLastFriday(D ateTime dateTime)
{
dateTime = dateTime.Subtra ct(new TimeSpan(1,0,0, 0));
if (dateTime.DayOf Week == DayOfWeek.Frida y)
{
lastFriday = dateTime;
return;
}
else
GetLastFriday(d ateTime);
}
}

Remember to add a check so your method doesnt execute more than 7 times
(days in a week) or you could get a stack overflow if things go wrong
Not only is it unnecessarily complex it is also incorrect. If you started
with Saturday it would return the Friday from the same week not "Friday Of
Last Week".

PS
>
On Nov 16, 1:14 pm, "sherifffruitfl y" <sherifffruit.. .@gmail.com>
wrote:
>Hi all,

This is how I'm currently getting Friday of last week. It strikes me as
cumbersome. Is there a slicker/more elegant way?

Thanks for any ideas,

cdj

private string prevFridayStrin g(DateTime day)
{
DateTime rv;
int offset = 0;

switch (day.DayOfWeek)
{
case DayOfWeek.Sunda y:
offset = 5;
break;
case DayOfWeek.Monda y:
offset = 4;
break;
case DayOfWeek.Tuesd ay:
offset = 3;
break;
case DayOfWeek.Wedne sday:
offset = 2;
break;
case DayOfWeek.Thurs day:
offset = 1;
break;
case DayOfWeek.Frida y:
offset = 0;
break;
case DayOfWeek.Satur day:
offset = -1;
break;
}

rv = day.AddDays(-7 + offset);
return rv.ToShortDateS tring();
}
Nov 16 '06 #8
Just for fun, here is the actual algorithm in C++ based on Zeller and
yes 0 for Sunday is how it was done:

GetFirstDayInMo nth
// Days since Sunday 0-6
// Based on Zeller
// ASSERT Year>1, Month>=1 && <=12.
int CCalendar::GetF irstDayInMonth( unsigned int Year, unsigned int Month)
{
const int day=1;
if (Month < 3) {
Month +=12;
Year -= 1;
}
return
((day+1+(Month* 2)+(int)((Month +1)*3/5)+Year+(int)(Y ear/4)-(int)(Year/100
)+(int)(Year/400))%7);
}

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 16 '06 #9

Jeff Louie wrote:
Just for fun, here is the actual algorithm in C++ based on Zeller and
yes 0 for Sunday is how it was done:
Wow - this turned into a whole lot more "fun" than I was expecting! I
especially love the recursive solution - lolol!

Nov 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
66847
by: strutsng | last post by:
<input type="file"> only allows the user to browse for files. How about "browse for folder" dialog? Can html/javascript do that? I couldn't find any syntax for that. If not, please advise what are the other approaches. please advise. thanks!!
24
7667
by: Hardy | last post by:
I'm pretty new in this field. when reading some 70x material, I met with this term but cannot catch its accurate meaning. who can help me? thanks in advance:)~
388
21879
by: maniac | last post by:
Hey guys, I'm new here, just a simple question. I'm learning to Program in C, and I was recommended a book called, "Mastering C Pointers", just asking if any of you have read it, and if it's worth the $25USD. I'm just looking for a book on Pointers, because from what I've read it's one of the toughest topics to understand. thanks in advanced.
1
3638
by: Chris | last post by:
I built small C# Web and Web Service applications in a training class last week. The applications worked in the class, but when I tried to run them again over the weekend, they both bombed. Instead of getting my Web page, or the Web Service page, I get a page full of error text (below). I am hoping the anwser will be obvious to someone. I've tried a few things to address the problem, including
32
4151
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
4
2476
by: trint | last post by:
Ok, I received info that this will work as a means of removing the border around a window that I create (which also loads an aspx file) in the firing file (aspx using javascript): OpenWindow = window.open("logon2.aspx", "remote", windowprops); But the code that removes its borders is in c#???: this.FormBorderStyle = FormBorderStyle.None; this.MaximizeBox = false; this.MinimizeBox = false;
10
4798
by: craig.keightley | last post by:
I am trying to get the next row within a loop for a script i am developing... I need to display a final table row within the table that i have displayed on the page, but i only want to show it if value of the current field is not the same value of the next row. eg:
3
2624
by: sbaird | last post by:
Aloha from Hawaii, I'm beating my head on the wall here. I have a recruiting contact managment database I'm trying to create. Managers (there ar 14 of them) have to make a certain number of recruiting calls per week, and so many of them have to result in at least an appointment. However, the "week" is Wednesday, 12:01pm to the following Wednesday, 12:00noon. So here are my questions... 1) Is there a way to change the standard week...
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9873
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9846
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8713
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3359
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.