Guest User

Untitled

a guest
Nov 18th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. ### これは何?
  2. 指定日時のX営業日前を計算するJavaのサンプルコード
  3.  
  4. * 仕様
  5. * 計算対象はコードに埋め込み m(_ _)m
  6. * 土日は何もしなくても、営業日外としてる
  7. * その他に営業日外としたい日は `holiday.txt` に書いておく
  8. ```
  9. [tomohiro.koike@ java]$ cat holiday.txt
  10. 2018-11-3
  11. 2018-11-15
  12. ```
  13.  
  14. ```eigyoubi_keisan.java
  15. import java.util.Calendar;
  16. import java.io.*;
  17.  
  18. class EigyoubiKeisan {
  19.  
  20. public static void main(String[] args) {
  21.  
  22. String target = "20181115";
  23. int num = 9; // 営業日
  24.  
  25. int year = Integer.parseInt(target.substring(0,4));
  26. int month = Integer.parseInt(target.substring(4,6))-1; // これで正しい
  27. int day = Integer.parseInt(target.substring(6,8));
  28.  
  29. Calendar cal = Calendar.getInstance();
  30.  
  31. //calにコマンドライン引数1で指定された年、月、日を設定する
  32. cal.set(year, month, day);
  33.  
  34. // 休日ファイルを読み込んで配列に入れとく
  35. String str[] = new String[100]; //とりあえず祝日は100件分
  36. int cnt=0;
  37. try {
  38. FileReader in = new FileReader("holiday.txt");
  39. BufferedReader br = new BufferedReader(in);
  40. String line;
  41. while ((line = br.readLine()) != null) {
  42. str[cnt] = line;
  43. cnt++;
  44. }
  45.  
  46. br.close();
  47. in.close();
  48. } catch (IOException e) {
  49. System.out.println(e);
  50. }
  51.  
  52. for (;0<num;) {
  53.  
  54. cal.add(Calendar.DATE, -1);
  55. String date = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.DATE);
  56. System.out.println(date);
  57.  
  58. // 土日だったら飛ばす
  59. if ( cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY ||
  60. cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY ) {
  61. continue;
  62. }
  63.  
  64. // 配列に入れた休日だったら飛ばす
  65. int flg = 0;
  66. for (int i=0;i<cnt;i++) {
  67. if (date.equals(str[i])) {
  68. flg = 1;
  69. break;
  70. }
  71. }
  72. if (flg==1) {
  73. continue;
  74. }
  75.  
  76. // そうでなければデクリメント
  77. num--;
  78.  
  79. }
  80.  
  81. System.out.println( String.format(
  82. "%1$tY年%1$tB%1$te日%1$ta曜日です。", cal));
  83.  
  84. }
  85. }
  86.  
  87. ```
Add Comment
Please, Sign In to add comment