获取月份的周时间段

包括C#方法和SQL方法。

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("输入日期,并回车(0退出):");
            string d1 = Console.ReadLine();
            while (d1 != "0")
            {
                DateTime dt = Convert.ToDateTime(d1);
                List<MyDate> datelist = DateUtil.GetWeekOfMonth(dt);
                Console.WriteLine(dt.Year+"年"+dt.Month+"月包含【"+datelist.Count+"】周:");
                foreach (var d in datelist)
                {
                    Console.WriteLine(d.firstDate + "\t" + d.lastDate);
                }
                d1 = Console.ReadLine();
            }
        }
    }

    class DateUtil{
        #region 获取时间(周,月)
        public static DateTime GetWeekDateStart(DateTime? date)
        {
            DateTime currentdate = date.HasValue ? date.Value : DateTime.Now;
            //本周
            int weeknow = Convert.ToInt32(currentdate.DayOfWeek);
            //星期日 获取weeknow为0
            weeknow = weeknow == 0 ? 7 : weeknow;
            int daydiff = (-1) * weeknow + 1;
            //本周第一天
            return currentdate.AddDays(daydiff);
        }
        public static DateTime GetWeekDateEnd(DateTime? date)
        {
            DateTime currentdate = date.HasValue ? date.Value : DateTime.Now;
            //本周
            int weeknow = Convert.ToInt32(currentdate.DayOfWeek);
            //星期日 获取weeknow为0
            weeknow = weeknow == 0 ? 7 : weeknow;
            int dayadd = 7 - weeknow;
            //本周最后一天
            return currentdate.AddDays(dayadd);
        }
        public static DateTime GetMonthDateStart(DateTime? date)
        {
            DateTime currentdate = date.HasValue ? date.Value : DateTime.Now;
            //本月第一天时间
            DateTime firstDate = currentdate.AddDays(-(currentdate.Day) + 1);
            return firstDate;
        }
        public static DateTime GetMonthDateEnd(DateTime? date)
        {
            DateTime currentdate = date.HasValue ? date.Value : DateTime.Now;
            DateTime dt = currentdate;
            //将本月月数+1
            DateTime dt2 = dt.AddMonths(1);
            //本月最后一天时间
            DateTime lastDate = dt2.AddDays(-(dt.Day));
            return lastDate;
        }

        /// <summary>
        /// 获取月份内的周时间段
        /// </summary>
        /// <param name="crdate">时间</param>
        /// <returns>当月周时间段</returns>
        public static List<MyDate> GetWeekOfMonth(DateTime? crdate)
        {
            List<MyDate> dateList = new List<MyDate>();

            DateTime currentdate = crdate.HasValue ? crdate.Value : DateTime.Now;
            DateTime firstDayofMonth = GetMonthDateStart(currentdate);
            DateTime lastDayofMonth = GetMonthDateEnd(currentdate);

            DateTime Week1firstday = GetWeekDateStart(firstDayofMonth);
            Week1firstday = Week1firstday < firstDayofMonth ? firstDayofMonth : Week1firstday;

            //第一周
            MyDate date1 = new MyDate();
            date1.firstDate = Week1firstday;
            date1.lastDate = GetWeekDateEnd(firstDayofMonth);
            dateList.Add(date1);
            //第二周
            MyDate date2 = new MyDate();
            DateTime Week2firstday = Week1firstday.AddDays(7);
            date2.firstDate = GetWeekDateStart(Week2firstday); ;
            date2.lastDate = GetWeekDateEnd(Week2firstday);
            dateList.Add(date2);
            //第三周
            MyDate date3 = new MyDate();
            DateTime Week3firstday = Week2firstday.AddDays(7);
            date3.firstDate = GetWeekDateStart(Week3firstday); ;
            date3.lastDate = GetWeekDateEnd(Week3firstday);
            dateList.Add(date3);
            //第四周
            MyDate date4 = new MyDate();
            DateTime Week4firstday = Week3firstday.AddDays(7);
            if (Week4firstday > lastDayofMonth)
            { Week4firstday = lastDayofMonth; }
            date4.firstDate = GetWeekDateStart(Week4firstday);
            date4.lastDate = GetWeekDateEnd(Week4firstday);
            if (date4.firstDate > lastDayofMonth)
            {
                return dateList;
            }
            if (date4.lastDate >= lastDayofMonth)
            {
                date4.lastDate = lastDayofMonth;
                dateList.Add(date4);
                return dateList;
            }
            dateList.Add(date4);
            //第五周
            MyDate date5 = new MyDate();
            DateTime Week5firstday = Week4firstday.AddDays(7);
            if (Week5firstday > lastDayofMonth)
            { Week5firstday = lastDayofMonth; }
            date5.firstDate = GetWeekDateStart(Week5firstday);
            date5.lastDate = GetWeekDateEnd(Week5firstday);
            if (date5.firstDate > lastDayofMonth)
            {
                return dateList;
            }
            if (date5.lastDate >= lastDayofMonth)
            {
                date5.lastDate = lastDayofMonth;
                dateList.Add(date5);
                return dateList;
            }
            dateList.Add(date5);
            //第六周
            MyDate date6 = new MyDate();
            DateTime Week6firstday = Week5firstday.AddDays(7);
            if (Week6firstday > lastDayofMonth)
            { Week6firstday = lastDayofMonth; }
            date6.firstDate = GetWeekDateStart(Week6firstday);
            date6.lastDate = GetWeekDateEnd(Week6firstday);
            if (date6.firstDate > lastDayofMonth)
            {
                return dateList;
            }
            if (date6.lastDate >= lastDayofMonth)
            {
                date6.lastDate = lastDayofMonth;
                dateList.Add(date6);
                return dateList;
            }
            dateList.Add(date6);
            return dateList;
        }
        #endregion
    }

    class MyDate
    {
        public DateTime firstDate { get; set; }
        public DateTime lastDate { get; set; }
    }
}

测试示例:

SQL

DECLARE @ym VARCHAR(7)
SET @ym = ‘2013-12‘
SET datefirst 1
SELECT  wk ,
        MIN(d) d1 ,
        MAX(d) d2
FROM    ( SELECT    DATEPART(wk, d) wk ,
                    d
          FROM      ( SELECT    DATEADD(D, number, @ym + ‘-01‘) d
                      FROM      master..spt_values
                      WHERE     type = ‘p‘
                                AND CONVERT(VARCHAR(7), DATEADD(D, number,
                                                              @ym + ‘-01‘), 120) = @ym
                    ) t
        ) t
GROUP BY wk

测试示例:

另mark周几获取方法

public string Week()
        {
            string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string week = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];
            return week;
        }

获取月份的周时间段

时间: 2024-11-06 03:44:44

获取月份的周时间段的相关文章

如何获取两个任意时间段内的所有日期(及其他处理日期时间的方法总结)

(1)用一下方法获取两个任意时间段内的所有日期,代码如下: #1.将字符串转换成datetime类型 def strtodatetime(datestr,format): return datetime.datetime.strptime(datestr,format) #2.时间转换成字符串,格式为2008-08-02 def datetostr(date): return str(date)[0:10] #3.两个日期相隔多少天,例:2008-10-03和2008-10-01是相隔两天 de

Java获取某年某周的第一天

1.设计源码 FirstDayOfWeek.java: /** * @Title:FirstDayOfWeek.java * @Package:com.you.freemarker.model * @Description:获取某年某周的第一天 * @author:Youhaidong(游海东) * @date:2014-5-29 下午11:29:53 * @version V1.0 */ package com.you.freemarker.model; import java.text.Si

Java获取某年某周的最后一天

1.设计源码 LastDayOfWeek.java: /** * @Title:LastDayOfWeek.java * @Package:com.you.freemarker.model * @Description:获取某年某周的最后一天 * @author:Youhaidong(游海东) * @date:2014-5-29 下午11:42:27 * @version V1.0 */ package com.you.freemarker.model; import java.text.Sim

Sql 获取当前日期是周几和WeekDay的Name

在Sql Server中,可以通过设置DataFirst选项来设置一周的第一天 语法: SET DATEFIRST { number | @number_var } Sets the first day of the week to a number from 1 through 7 1,可以通过@@datefirst来获取设置的值 set DATEFIRST 1 select @@datefirst 2,使用函数datepart函数获取当天是周几 set DATEFIRST 1 --selec

php 获取最近一周,一个月,一年

<?php //PRC是中国的意思,这段代码是把默认时区设置成了中国标准时间.date_default_timezone_set('PRC');/** * 获取最近一周,一个月,一年 * */function getLatelyTime($type = ''){ $now = time(); $result = []; if($type == 'week'){ //最近一周 for($i=0;$i<7;$i++){ $result[] = date('Y-m-d',strtotime('-'.

js日期计算及快速获取周、月、季度起止日,获取指定日期周数以及星期几的小例子

JS获取日期时遇到如下需求,根据某年某周获取一周的日期.如开始日期规定为星期四到下一周的星期五为一周. 格式化日期: function getNowFormatDate(theDate) { var day = theDate; var Year = 0; var Month = 0; var Day = 0; var CurrentDate = ""; // 初始化时间 Year= day.getFullYear();// ie火狐下都可以 Month= day.getMonth()

oracle中从指定日期中获取月份或者部分数据

从指定日期中获取部分数据: 如月份: select to_CHAR(sysdate,'MM') FROM DUAL; 或者: select extract(month from sysdate) from dual; 又或者最笨的方法.用to_char()先把日期转化为指定格式的字符串,在通过substr()这个取到想要的数据. select substr(to_char(sysdate,'yyyy-mm-dd'),6,2) from dual; 获取日期其他部分数据和上方法一样.

js 获取月份 格式yy-mm-dd

/** * 获取上一个月 * * @date 格式为yyyy-mm-dd的日期,如:2014-01-25 */ function getPreMonth(date) { var arr = date.split('-'); var year = arr[0]; //获取当前日期的年份 var month = arr[1]; //获取当前日期的月份 var day = arr[2]; //获取当前日期的日 var days = new Date(year, month, 0); days = da

通过当前时间获取当前所在周的7天的时间

<!doctype html><html><head><meta charset="utf-8"><title>获取当前时间所在周的日期</title><script>//优化整合以后的代码function displayDate02(){  var date = new Date();  var year = date.getFullYear();  var mouths = date.getMont