Skip to content

Instantly share code, notes, and snippets.

@Myoga1012
Last active January 30, 2023 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Myoga1012/2a8bba2bbc850de06a90 to your computer and use it in GitHub Desktop.
Save Myoga1012/2a8bba2bbc850de06a90 to your computer and use it in GitHub Desktop.
C#でカレンダーを出力するソースコードです。
// 名前 : Myoga Screw-bright (旧名:Myoga S. Tomonaka)
// Twitter : https://twitter.com/Myoga1012
using System;
namespace Myoga1012_Cal {
class Program {
static void Main( string[] args ) {
// 現在の日付を取得から当月1日を表すインスタンスを生成します。
DateTime now1 = new DateTime( DateTime.Today.Year, DateTime.Today.Month, 1 );
// 当月1日からその曜日分だけ引きます。
DateTime curDay = now1.AddDays( -( int )now1.DayOfWeek );
// カレンダーを出力します。
do {
// 日付を出力します(最大2桁なので、最小フィールド幅を3と指定し、右寄せかつ日付間にスペースを開けます)。
// もし、curDayが前月であれば、日付の代わりに空白スペースを出力します。
// こうすることで1日の曜日に合わせてオフセットすることができます。
if( curDay >= now1 ) Console.Write( "{0, 3}", curDay.Day ); else Console.Write( " " );
// curDayが土曜日または当月末日であれば、改行します。
if( curDay.DayOfWeek == DayOfWeek.Saturday ||
curDay.Month == now1.Month && curDay.Day == DateTime.DaysInMonth( now1.Year, now1.Month ) ) Console.WriteLine();
// curDayを1日分進めて、翌月になるまで繰り返します。
} while( ( curDay = curDay.AddDays( 1.0 ) ).Month == now1.Month || curDay <= now1 );
}
}
}
// Calender.cs
// Copyright (c) 2014 Myoga-TN.net All Rights Reserved.
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// 旧コードです。
using System;
namespace Myoga1012_Cal {
class Program {
static void Main( string[] args ) {
// 現在の日付を取得し、当月1日を表すインスタンスを生成します。
DateTime now = DateTime.Today;
DateTime day = new DateTime( now.Year, now.Month, 1 );
// 1日の曜日に合わせてオフセットします。
for( int i = 0; i < ( int )day.DayOfWeek; i++ ) Console.Write( " " );
// カレンダーを出力します。
do {
// 日付を出力します(最大2桁なので、最小フィールド幅を3と指定し、右寄せかつ日付間にスペースを開けます)。
Console.Write( "{0, 3}", day.Day );
// dayが土曜日または月末日であれば、改行します。
if( day.DayOfWeek == DayOfWeek.Saturday ||
day.Day == DateTime.DaysInMonth( now.Year, now.Month ) ) Console.WriteLine();
// dayを1日分進めて、月が変わるまで繰り返します。
} while( ( day = day.AddDays( 1.0 ) ).Month == now.Month );
}
}
}
@Myoga1012
Copy link
Author

月末が土曜日だと、最後に1行空いてしまうので、条件文で回避させました。

@Myoga1012
Copy link
Author

[2014/11/26][Calendar.cs] : 前月末日で改行してしまうバグがありましたので修正しました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment