我正在使用ColdFusion 9.0.1。
我正在每个星期一午夜创建比赛。我需要使用ColdFusion(但我相信其他语言的逻辑是相同的)来查找最近一个星期一的日期。确定该日期后,我会将该日期删除到SQL语句中以获取当前的排名和过去的结果。
那么,我需要哪些功能才能找到最近的星期一?
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);
}
}
答案 0 :(得分:10)
您也可以从2(即星期一)扣除当周的当天某天
<!--- 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>
答案 1 :(得分:6)
伪代码:
Get the current day
Loop
Check if it's Monday
If yes, break out of the loop
Substract one
Next loop
在ColdFusion中,使用DateAdd("d", -1, date)
减去一天,并使用DayOfWeek(date)
检查星期一,其中星期一返回2.
答案 2 :(得分:0)
您也可以使用java Calendar类来完成它。
ColdFusion日期方法在内部使用的是什么。
<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