OracleでFIRST_DAY

先輩に聞く前に、

  • まずよく考えみて、
  • わからなければ調べて、
  • それでもダメなら聞く、

という癖をつけないとなあ。厳しいぞ。

/* Oracle PL/SQLで日付からその月の1日を求める*/

/* to_date、to_charを使えるなら、考えればできる */
create or replace function first_day(thedate date) return date is
begin
    return to_date(to_char(thedate,'YYYY-MM')||'-01','YYYY-MM-DD');
end;

/* 調べてみれば、こっちがスマートだとわかる */
create or replace function first_day(thedate date) return date is
begin
    return trunc(thedate,'MONTH');
end;

/***** ついでに *****/

/* 年の最初の日 1月1日 */
create or replace function first_day2(thedate date) return date is
begin
    return trunc(thedate,'YEAR');
end;

/* 週の始まり日曜日(※NLSの設定次第) */
create or replace function first_day3(thedate date) return date is
begin
    return trunc(thedate,'DAY');
end;

最後に問題。月の日数を求めるにはどうする?

This entry was posted in Code, Tech and tagged . Bookmark the permalink.

2 Responses to OracleでFIRST_DAY

  1. nakunaru says:

    NLSはクライアント単位でカスタムできちゃうので、勝手に変更されない保障があるのならNLS依存でも構わないと思います。(あるいはアプリ起動時にALTER SESSIONで毎回設定するとか)
    お目汚し失礼しました。

  2. nakunaru says:

    thedate + (1 – to_char(thedate, ’D’))
    とするとNLSに依存しないで週の頭の日付が取れるかもしれません。
    ちゃんと検証してないのでアレですが。

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>