How to find the most recent past Monday?

有些话、适合烂在心里 提交于 2019-12-11 12:06:31

问题


I am using ColdFusion 9.0.1.

I am creating a contest each Monday at midnight. I need to use ColdFusion (but I am sure the logic is the same for other languages) to find the date of the most recent past Monday. Once I determine that date, I will drop that date into a SQL Statement to get the current standings and past results.

So, what functions do I need to find the most recent past Monday?

ANSWER

Dates = structNew();
Dates.CurrentDay = dateFormat(now(), "yyyy-mm-dd");
// LOOP MAX OF SEVEN TIMES
for (i = 1; i lte 7; i++) {
    // IF CURRENT DAY OF WEEK IS MONDAY SET AND BREAK
    if (dayOfWeek(Dates.CurrentDay) == 2) {
        Dates.BikeOfTheWeekDate = Dates.CurrentDay;
        break; 
    // IF CURRENT DAY OF WEEK IS NOT MONDAY SUBTRACT DAY
    } else {
        Dates.CurrentDay = dateAdd("d", -1, Dates.CurrentDay);
    }
}

回答1:


Pseudocode:

Get the current day
Loop
    Check if it's Monday
        If yes, break out of the loop
    Substract one
Next loop

In ColdFusion, substract one day with DateAdd("d", -1, date) and check for Monday with DayOfWeek(date) which returns 2 for Monday.




回答2:


You could also just deduct the current day of week from 2 (ie Monday)

<!--- All days except Sunday (ie 2-Monday,...,7-Saturday) --->
<cfif dayOfWeek(currentDate) gt 1>
    <cfset mostRecentMonday = dateAdd("d", 2-dayOfWeek(currentDate), currentDate)>
<cfelse>
    <cfset mostRecentMonday = dateAdd("d", -6, currentDate)>
</cfif>



回答3:


You can also do it using the java Calendar class.

Which is what the ColdFusion date methods use internally.

<cfscript>
var cal = createObject( 'java', 'java.util.Calendar' ).getInstance();
cal.setTime( now() );

// if the (7) day of week is before (2) monday, we want the previous week
// decrement the (3) week of year
if ( cal.get(7) < 2 ) {
    cal.set( 3, cal.get(3) - 1 );
}

// set the (7) day of week back to (2) monday
cal.set( 7, 2 );    // 7 = day of week, 2 = monday

// reset time fields back to 0, aka midnight
cal.set( 11, 0 );   // 11 = hour of day
cal.set( 12, 0 );   // 12 = minute
cal.set( 13, 0 );   // 13 = second
cal.set( 14, 0 );   // 14 = millisecond

// get the last monday Date
var lastMonday = cal.getTime();

// cal.getTime() returns a java.util.Date
// if you want to convert the date to a ColdFusion OleDateTime, you can like so
var lastMonday = dateAdd( 'd', 0, cal.getTime() );

// or like this
var lastMonday = createObject( 'java', 'coldfusion.runtime.OleDateTime' ).init( cal.getTime() );
<cfscript>

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html



来源:https://stackoverflow.com/questions/9048768/how-to-find-the-most-recent-past-monday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!