30

月または年のすべての日を持つ方法はありますか? 日付ピッカーで特定の日を無効にするためにこれを探しています。バックオフィスにこれらの日を選択して無効にするページがあります。

したがって、月のすべての日を表示し、各日の下に「アクティブ化または非アクティブ化」ボタンを追加する必要があります。Date オブジェクトでこれらの日を見つける方法はありますか? たとえば、このリンクを見つけました:月のすべての日を表示していますが、よくわかりません。さらに、Javaです。JavaScriptで解決策を見つけようとしています。

ご協力ありがとうございました

4

10 に答える 10

95

月のすべての日のリストを取得するには、月Dateの最初の日に開始し、月が変わるまで日を増やします。

/**
 * @param {int} The month number, 0 based
 * @param {int} The year, not zero based, required to account for leap years
 * @return {Date[]} List with date objects for each day of the month
 */
function getDaysInMonth(month, year) {
  var date = new Date(year, month, 1);
  var days = [];
  while (date.getMonth() === month) {
    days.push(new Date(date));
    date.setDate(date.getDate() + 1);
  }
  return days;
}

UTCバージョン

いくつかのコメントに応えて、ローカライズされたタイムゾーンを返す標準メソッドの代わりにUTCメソッドを呼び出したい場合に備えて、UTCメソッドを使用するバージョンを作成しました。

これがうまくいかなかったというコメントの原因だと思います。getUTCMonth/Day/Hoursタイムゾーンを変換して違いを表示しようとしている場合を除き、通常、メソッドをインスタンス化した場合は必ずメソッドを呼び出しDate.UTC、その逆も同様です。

function getDaysInMonthUTC(month, year) {
  var date = new Date(Date.UTC(year, month, 1));
  var days = [];
  while (date.getUTCMonth() === month) {
    days.push(new Date(date));
    date.setUTCDate(date.getUTCDate() + 1);
  }
  return days;
}

この回答の編集

このスクリプトに問題があると思われる場合は、お気軽に次のことを行ってください。

  • まず、以下の既存の単体テストを参照してください
  • 壊れていることを証明するテストケースを作成します。
  • コードを修正し、既存のテストに合格することを確認します。

ユニットテスト

/**
 * @param {int} The month number, 0 based
 * @param {int} The year, not zero based, required to account for leap years
 * @return {Date[]} List with date objects for each day of the month
 */
function getDaysInMonthUTC(month, year) {
  var date = new Date(Date.UTC(year, month, 1));
  var days = [];
  while (date.getUTCMonth() === month) {
    days.push(new Date(date));
    date.setUTCDate(date.getUTCDate() + 1);
  }
  return days;
}

function getDaysInMonth(month, year) {
  var date = new Date(year, month, 1);
  var days = [];
  while (date.getMonth() === month) {
    days.push(new Date(date));
    date.setDate(date.getDate() + 1);
  }
  return days;
}

const days2020 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const days2021 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

describe("getDaysInMonthUTC", function() {
  it("gets day counts for leap years", function() {
    const actual = days2020.map(
      (day, index) => getDaysInMonthUTC(index, 2020).length
    );
    expect(actual).toEqual(days2020);
  });

  it("gets day counts for non-leap years", function() {
    const actual = days2021.map(
      (day, index) => getDaysInMonthUTC(index, 2021).length
    );
    expect(actual).toEqual(days2021);
  });
});


describe("getDaysInMonth", function() {
  it("gets day counts for leap years", function() {
    const actual = days2020.map(
      (day, index) => getDaysInMonth(index, 2020).length
    );
    expect(actual).toEqual(days2020);
  });

  it("gets day counts for non-leap years", function() {
    const actual = days2021.map(
      (day, index) => getDaysInMonth(index, 2021).length
    );
    expect(actual).toEqual(days2021);
  });
});

// load jasmine htmlReporter
(function() {
  var env = jasmine.getEnv();
  env.addReporter(new jasmine.HtmlReporter());
  env.execute();
}());
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<link href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet"/>

于 2012-10-30T20:07:28.563 に答える
4

標準の無効な日付のdatepickerが機能するかどうかは説明からわかりません。そのため、質問に直接回答します。

これを行うことにより、1か月の日の配列をかなり簡単に作成できます。

var numOfDays = new Date(2012, 10, 0).getDate(); //use 0 here and the actual month
var days = new Array();

//This will construct an array with all the elements represent the day of the week 
//(i.e. Oct 30th would be days[30-1] or days[29]) and the value would be the actual 
//day of the week (i.e. Tuesday which is representing by the number 2)
for(var i=0;i<=numOfDays;i++)
{
    days[i] = new Date(2012,9,i+1).getDay(); //use month-1 here            
}
//This will give you a number from 0 - 6 which represents (Sunday - Saturday)
alert(days[29]); 

その一連の日を使用すると、ほとんど何でもでき、曜日も知ることができます。

于 2012-10-30T20:00:03.133 に答える
1

これは、その月の最終日を決定するために各月を実行する loopp です。Javascript の Date オブジェクトは月を 0 からインデックス付けします。日を 0 に設定すると、前月の最終日に戻ります。2月のうるう年の最終日を決定するのに便利

Date( 2012, 12, 0)2012 年 12 月 31 日に戻ります

Date (2012,0,0)戻ります 12 月 31,2011

把握することが最も重要なのは2月です

Date ( 2012,3,0)今年はうるう年から 2 月 29 日を返します

var mos=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']

for (i = 0; i < 12; i++) {
    var lastDate = new Date(2012, i+1, 0);
    $('body').append('Last day of ' + mos[i] + ' is ' + lastDate.getDate()+'<br>')
}

デモ: http://jsfiddle.net/5k8sn/1/

于 2012-10-30T20:11:05.807 に答える
1

jQuery datepicker を使用して、ご要望の機能を実装しました。

まず、無効にするバック オフィスで選択したすべての日付を配列に追加します。

// format yyyy-mm-dd
var disabledDates = [
    "2012-10-01",
    "2012-10-02",
    "2012-10-30",
    "2012-09-12"
];

次に、2 つの関数で日付ピッカーを指定します

$("#datepicker").datepicker({

    // only enable date if dateEnabled returns [true]
    beforeShowDay: dateEnabled,

    // once a date has been selected call dateSelected
    onSelect: dateSelected
});

必要な関数の定義は次のとおりです。

function dateEnabled( d ) {

    // if date found in array disable date
    if( disabledDates.indexOf( getDate( d ) ) > -1 ) {

        return [false];

    } else {

        return [true] ;

    }
}  

配列内の日付と比較するために、日付を文字列に変換します

function getDate( d ) {
    var day,
        month,
        year;

    day = d.getDate( );
    month = d.getMonth( ) + 1; // add 1 as getMonth returns 0 - 11
    year = d.getFullYear( );

    if( month < 10 ) month = "0" + month;
    if( day < 10 ) day = "0" + day;
    return year + "-" + month + "-" + day;
}

日付が選択されたら、それを処理します

function dateSelected( d ) { 
   // do stuff with string representation of date                                          
}

ここにフィドルがありますhttp://jsfiddle.net/KYzaR/7/

Array.indexOf は ECMA-262 標準に最近追加されたものであるため、IE7 および IE8 の場合はサポートされていないことに注意してください。次の MDN ページでは、これらのブラウザーに Array.indexOf を実装するコードを提供していますhttps://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

于 2012-10-30T23:32:04.637 に答える
0

日付ピッカーで日付を無効にするには、ここで説明されている回答を使用できます:
https://stackoverflow.com/a/12061715/48082

複数の日付を選択するには (バックオフィス アプリのように)、次のプラグインを使用できます:
http://multidatespickr.sourceforge.net/

于 2012-10-30T19:43:58.457 に答える
0

解決策があります。ハッピーコーディング❤️ !! 注: 0=1 月、1=2 月など。 例 w3schools

const getDays = (month, year) => {
    let date = new Date(`${year}-${parseInt(month)+1}-01`);
    let days = [];
    while (date.getMonth() === parseInt(month)) {
        days.push(date.getDate());
        date.setDate(date.getDate() + 1);
    }
    return days;
}
于 2021-03-19T11:30:49.407 に答える