반응형

Using the Console

The JavaScript Console provides two primary functions for developers testing web pages and applications:

  • A place to log diagnostic information using methods provided by the Console API, such as console.log(), or console.profile().
  • A shell prompt where you can enter commands and interact with the document and the Chrome DevTools. You can evaluate expressions directly in the Console, and can also use the methods provided by the Command Line API, such as $() command for selecting elements, or profile() to start the CPU profiler.

This documentation provides an overview and common uses of these two APIs. You can also browse the Console API and Command Line API reference guides.

Basic operation

Opening the Console

The JavaScript Console is available in two modes within Chrome DevTools: the primary Console tab, or as a split-view you can display while on another tab (such as Elements or Sources).

To open the Console tab, do one of the following:

  • Use the keyboard shortcut Command - Option - J (Mac) or Control -Shift -J (Windows/Linux).
  • Select View > Developer > JavaScript Console.

Console panel view

To toggle a split-view of the Console on another tab, press the Esc key on your keyboard, or click the Show/Hide Console button in the bottom left corner of the Chrome DevTools window. In the following screenshot the Console split-view is shown with the Elements panel.

Console split-view

Clearing the console history

To clear the console's history, do one of the following:

  • Right-click or Ctrl-click anywhere in the Console and choose Clear Console from the context menu that appears.
  • Enter the clear() Command Line API at the shell prompt.
  • Invoke console.clear() Console API from JavaScript.
  • Use the keyboard shortcut ⌘K or ⌃L (Mac) Control - L (Windows and Linux).

By default, the console history is cleared when you navigate to another page. You can change this behavior by enabling Preserve log upon navigation in the Console area of the Settings dialog (see Console preferences).

Console settings

The Console has two global settings you can modify in the General tab of the DevTools Settings dialog:

  • Log XMLHTTPRequests—determines if each XMLHTTPRequest is logged to the Console panel.
  • Preserve log upon navigation—determines if console history for the current page is preserved when you navigate to another page. By default, both of these settings are disabled.

You can also change these settings by right-clicking anywhere in the Console to bring up the context menu.

Console panel view

Using the Console API

The Console API is collection of methods provided by the global console object defined by DevTools. One of the API's main purposes is to log information (such as a property value, or an entire objects or DOM element) to the console while your application is running. You can also group output visually in the console to reduce visual clutter.

Writing to the console

The console.log() method takes one or more expressions as parameters and writes their current values to the console. For example:

var a = document.createElement('p');
a
.appendChild(document.createTextNode('foo'));
a
.appendChild(document.createTextNode('bar'));
console
.log("Node count: " + a.childNodes.length);

Console log output

Instead of concatenating expressions together with the "+" operator (as shown above), you can put each in its own method parameter and they will be joined together in a space-delimited line.

console.log("Node count:", a.childNodes.length, "and the current time is:", Date.now());

Console log output

Errors and warnings

The console.error() method displays a red icon along with the message text, which is colored red.

function connectToServer() {
console
.error("Error: %s (%i)", "Server is not responding",500);
}
connectToServer
();

The console.warn() method displays a yellow warning icon with the message text.

if(a.childNodes.length < 3 ) {
console
.warn('Warning! Too few nodes (%d)', a.childNodes.length);
}

Example of console.warn()

Assertions

The console.assert() method conditionally displays an error string (its second parameter) only if its first parameter evaluates to false. For instance, in the following example an error message is written to the console only if the number of child nodes belonging to the list element is greater than 500.

console.assert(list.childNodes.length < 500, "Node count is > 500");

Example of console.assert()

Filtering console output

You can quickly filter console output by its severity level--errors, warning, or standard log statements--by selecting one of the filter options along the bottom of the Console, as shown below.

Only show console.error() output

Filter options:

  • All—Shows all console output.
  • Errors—Only show output from console.error()
  • Warnings—Only show output from console.warn()
  • Logs—Only show output from console.log(), console.info() and console.debug().
  • Debug—Only show output from console.timeEnd() and other console output.

Grouping output

You can visually group related console output statements together in the console with the console.group() and groupEnd() commands.

var user = "jsmith", authenticated = false;
console
.group("Authentication phase");
console
.log("Authenticating user '%s'", user);
// authentication code here...
if (!authenticated) {
console
.log("User '%s' not authenticated.", user)
}
console
.groupEnd();

Logging group example

You can also nest logging groups. In the following example a logging group is created for the authentication phase of a login process. If the user is authenticated, a nested group is created for the authorization phase.

var user = "jsmith", authenticated = true, authorized = true;
// Top-level group
console
.group("Authenticating user '%s'", user);
if (authenticated) {
console
.log("User '%s' was authenticated", user);
// Start nested group
console
.group("Authorizing user '%s'", user);
if (authorized) {
console
.log("User '%s' was authorized.", user);
}
// End nested group
console
.groupEnd();
}
// End top-level group
console
.groupEnd();
console
.log("A group-less log trace.");

Nested logging group example

To create a group that is initially collapsed, use console.groupCollapsed() instead of console.group(), as shown below:

console.groupCollapsed("Authenticating user '%s'", user);
if (authenticated) {
...
}

Initially collapsed group

String substitution and formatting

The first parameter you pass to any of the console's logging methods (log() or error(), for example) may contain one or more format specifiers. A format specifier consists of a % symbol followed by a letter that indicates the formatting that should be applied to the inserted value (%s for strings, for example). The format specifier identifies where to substitute a value provided by a subsequent parameter value.

The following example using the %s (string) and %d (integer) formatters to insert values into the output string.

console.log("%s has %d points", "Sam", "100");

This would result in "Sam has 100 points" being logged to the console.

The following table lists the supported format specifiers and the formatting they apply:

Format specifier Description
%s Formats the value as a string.
%d or %i Formats the value as an integer.
%f Formats the object as a floating point value.
%o Formats the value as an expandable DOM element (as in the Elements panel).
%O Formats the value as an expandable JavaScript object.
%c Applies CSS style rules to output string specified by the second parameter.

In the following example the %d format specifier is substituted with the value of document.childNodes.length and formatted as an integer; the %f format specifier is substituted with the value returned by Date.now(), which is formatted as a floating point number.

console.log("Node count: %d, and the time is %f.", document.childNodes.length, Date.now());

Using format specifiers

Formatting DOM elements as JavaScript objects

By default, when you log a DOM element to the console it's displayed in an XML format, as in the Elements panel:

console.log(document.body.firstElementChild)

You can also log an element's JavaScript representation with the console.dir() method:

console.dir(document.body.firstElementChild);

Equivalently, you can us the %O format specifier with console.log():

console.log("%O", document.body.firstElementChild);

Styling console output with CSS

You use the %c format specifier to apply custom CSS rules to any string you write to the Console with console.log() or related methods.

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size:18pt");

Styling console output with CSS

Measuring how long something takes

You can use the console.time() and console.timeEnd() methods to measure how long a function or operation in your code takes to complete. You call console.time() at the point in your code where you want to start the timer and console.timeEnd() to stop the timer. The elapsed time between these two calls is displayed in the console.

console.time("Array initialize");
var array= new Array(1000000);
for (var i = array.length - 1; i >= 0; i--) {
array
[i] = new Object();
};
console
.timeEnd("Array initialize");

Example of using console.time() and timeEnd()

Marking the Timeline

The Timeline panel gives you a complete overview of where time is spent when loading and using your web app or page. The console.timeStamp() method marks the Timeline at the moment it was executed. This provides an easy way to correlate events in your application with other browser-related events, such as layout or paints.

In the following example the Timeline is marked when the application enters the AddResult() function's implementation.

function AddResult(name, result) {
console
.timeStamp("Adding result");
var text = name + ': ' + result;
var results = document.getElementById("results");
results
.innerHTML += (text + "<br>");
}

As shown in the following screenshot, the timeStamp() command annotates the Timeline in the following places:

  • A yellow vertical line in the Timeline's summary and detail views.
  • A record is added to the list of recorded events.

Timeline showing custom timestamp

Setting breakpoints in JavaScript

You can start a debugging session from your JavaScript code by calling the debugger command. For instance, in the following example the JavaScript debugger is opened when an object's brightness() function is invoked:

brightness : function() {
debugger;
var r = Math.floor(this.red*255);
var g = Math.floor(this.green*255);
var b = Math.floor(this.blue*255);
return (r * 77 + g * 150 + b * 29) >> 8;
}

Example of using debugger command

Using the Command Line API

In addition to being a place where you can log information from your application, the Console is also a shell prompt where you can directly evaluate expressions or issue commands provided by the Command Line API. This API provides the following features:

  • Convenience functions for selecting DOM elements
  • Methods for controlling the CPU profiler
  • Aliases for a number of Console API methods
  • Monitoring events
  • View event listeners registered on objects

Evaluating expressions

The Console attempts to evaluate any JavaScript expression you enter at the shell prompt, upon pressing the Return or Enter key. The Console provides auto-completion and tab-completion. As you type expressions, property names are automatically suggested. If there are multiple properties with the same prefix, pressing the Tab key cycles through them. Pressing the right arrow key accepts the current suggestion. The current suggestion is also accepted by pressing the Tab key if there is only one matched property.

To enter a multi-line expression at the shell prompt (such as a function definition) press Shift+Enter between lines.

Selecting elements

The Command Line API provides several methods to access DOM elements in your application. For example, the $() method returns the first element that matches the specified CSS selector, just like document.querySelector(). For instance, the following code returns the element with the ID "loginBtn".

$('#loginBtn');

The $$() command returns an array of all the elements that match the specified CSS selector, just like document.querySelectorAll(). For instance, the following displays selects all <button> elements with the CSS class "loginBtn":

$$('button.loginBtn');

Lastly, the x() method takes an XPath path as a parameter and returns an array of all elements that match the specified path. The following returns all the <script> elements that are children of the <body> tag:

$x('/html/body/script');

Inspecting DOM elements and JavaScript heap objects

The inspect() method takes a DOM element reference (or JavaScript reference) as a parameter and displays the element or object in the appropriate panel—the Elements panel for DOM elements, or the Profile panel for a JavaScript object.

For example, in the following screenshot the $() function is used to get a reference to an <li> element. Then the last evaluated expression property ($_) is passed to inspect() to open that element in the Elements panel.

Accessing recently selected elements and objects

Often when testing you'll select DOM elements—either directly in the Elements panel or using the Selection tool (magnifying glass)—so that you can further inspect the element. Or, when analyzing a memory snapshot in the Profiles panel, you might select a JavaScript object to further inspect it.

The Console remembers the last five elements (or heap objects) you've selected and makes them available as properties named $0, $1, $2, $3 and $4. The most recently selected element or object is available as $0, the second most as $1, and so forth.

The following screenshot shows the values of these properties after selecting three different elements in turn from the Elements panel:

Recently selected elements

Monitoring events

The monitorEvents() command monitors an object for one or more specified events. When an event occurs on the monitored object, the corresponding Event object is logged to the Console. You specify the object and the events you want to monitor on that object. For example, the following code enables event monitoring for every "resize" event on the global window object.

monitorEvents(window, "resize");

Monitoring window resize events

To monitor several events, you can pass an array of event names as the second parameter. The code below monitors both "mousedown" and "mouseup" events on the body of the document.

monitorEvents(document.body, ["mousedown", "mouseup"]);

You can also pass one of the supported "event types" that DevTools maps to a set of actual event names. For example, the "touch" event type cause DevTools to monitor "touchstart", "touchend", "touchmove", and "touchcancel" events on the target object.

monitorEvents($('#scrollBar'), "touch");

See monitorEvents() in the Console API Reference for a list of supported event types.

To stop monitoring events call unmonitorEvents(), passing the object to stop monitoring.

unmonitorEvents(window);

Controlling the CPU profiler

You can create JavaScript CPU profiles from the command line with the profile() and profileEnd() commands. You can optionally specify a name that's applied to the profile you create.

For example, the following shows an example of creating a new profile with the default name:

The new profile appears in the Profiles panel under the name "Profile 1":

If you specify a label for the new profile, it is used as the new profile's heading. If you create multiple profiles with the same name, they are grouped as individual runs under the same heading:

The result in the Profiles panel:

CPU profiles can be nested, for example:

profile("A");
profile
("B");
profileEnd
("B")
profileEnd
("A")

The calls to stop and start profiling do not need be properly nested. For example, the following works the same as the previous example:

profile("A");
profile
("B");
profileEnd
("A");
profileEnd
("B");

 

Posted by 1010
반응형
[펌]오라클 날짜 계산
출처 : http://www.zetswing.com/bbs/board.php?bo_table=ORACLE_TIP&wr_id=20&page=

1. Oracle에서의 날짜 특징

*oracle은 세기,년,월,일,시간,분,초의 내부숫자 형식으로 날짜를 저장합니다.
*디폴트 날짜형식은 'DD-MON-YY' 입니다.
*SYSDATE는 현재의 날짜와 시간을 리턴하는 함수입니다.(date타입)
ex : 2007-01-07 오후 10:34:00
*DUAL은 SYSDATE를 보기위해 사용된 dummy table입니다.

2.oracle에서의 날짜연산

* 날짜에서 숫자(날수)를 빼거나 더하여 날짜 결과를 리턴합니다. 결과는 날짜형식
* 날짜 사이의 일수를 알기 위하여 2개의 날짜를 뺍니다.
* 시간을 24로 나누어 날짜에 더합니다.
날짜 + 숫자 : 날짜 특정한 날로부터 몇일 후의 날짜 계산
날짜 - 숫자 : 날짜 특정한 날로부터 몇일 전의 날짜 계산
날짜 - 날짜 : 숫자 두 날짜 사이의 차이를 숫자로 계산

3.oracle에서의 날짜 컬럼데이타형

date 형

4. 월과 일을 문자로 출력시 한글로 나오는거 영문으로 나오게 하기

오라클 환경 설정에 따라 아래 쿼리를 실행시키면 "7월" 이라고 나올수 있다.
SELECT TO_CHAR(SYSDATE,'mon') FROM DUAL;

오라클 환경 설정에 따라 아래 쿼리를 실행시키면 "월요일" 이라고 나올수 있다.
SELECT TO_CHAR(sysdate,'day') FROM DUAL;

영문("Jul")으로 출력시키려면 아래 명령으로 환경설정을 변경한다.
ALTER SESSION SET NLS_LANGUAGE = 'AMERICAN';

※ 월요일, 화요일 형식이 아닌 월, 화 형식으로 나타내기
SELECT TO_CHAR(sysdate,'day') FROM DUAL;

5.날짜의 순서결과 데이타형

날짜 - 날짜 = 숫자
숫자 + 날짜 = 날짜
(날짜 - 날짜) + 날짜 = 날짜
날짜 + 날짜 = error


※ trunc함수를 날짜데이타에 사용하기

select sysdate from dual;
--2006-02-08 오전 12:11:05


select trunc(sysdate) from dual;
select trunc(sysdate,'dd') from dual;
--단지 시간을 없애고 날짜만 나오게 한다.
--2006-02-08


select trunc(sysdate,'d') from dual;
--시간을 없애고 일을 가장최근에 지난 일요일 일로 초기화합니다.(권장)
--2006-02-05


select trunc(sysdate,'d')+1 from dual;
--시간을 없애고 일을 가장최근에 지난 월요일 일로 초기화합니다.

select trunc(sysdate,'d')-1 from dual;
--시간을 없애고 일을 가장최근에 지난 토요일 일로 초기화합니다.


select trunc(sysdate,'ww') from dual;
--시간을 없애고 일을 가장최근에 지난 일요일 일로 초기화합니다.
--2006-02-05


select trunc(sysdate,'mm') from dual;
--시간을 없애고 일을 1로 초기화합니다.
--2006-02-01


select trunc(sysdate,'Y') from dual;
select trunc(sysdate,'YY') from dual;
select trunc(sysdate,'YYY') from dual;
select trunc(sysdate,'YYYY') from dual;
--시간을 없애고 년도는 올해 년도와 월과 일을 모두 1 로 변경하여 출력합니다.

ex. 2006-01-01

SELECT TO_CHAR(SYSDATE,'YYYYMMDD') FROM DUAL;
SELECT TO_CHAR('20070715') FROM DUAL;
-- 현재 날짜를 YYYYMMDD 형식으로 출력한다.(자주사용)

8자리일자와 6자리시간을 문자열로 출력
select
to_char(sysdate, 'yyyymmdd') ,
to_char(sysdate, 'hh24miss')
from dual

6.날짜 관련 쿼리 예제

해당일이 그달의 몇째주인지 알아내기(w)
SELECT to_char(to_date('20061224', 'yyyymmdd'), 'w') FROM dual;

해당년도의 전체 일수 구하기
SELECT to_date('20001231', 'YYYYMMDD') - to_date('20000101', 'YYYYMMDD') from dual
SELECT TO_CHAR (TO_DATE (:yyyy || '1231'), 'ddd') ilsu FROM DUAL
-- 위의 쿼리는 년도를 변수로 사용하였다.


UPDATE tab1 SET logdate = sysdate, ismodify = 1 WHERE logdate < sysdate-7
--기록된 날짜(LOGDATE)가 현재날짜(SYSDATE)로부터 일주일이 지났으면
--SYSDATE를LOGDATE에 쓰고 날짜가 바뀌었다는 기록을 남기는(ISMODYFY = 1) 쿼리

UPDATE tab1 SET logdate = sysdate, ismodify = 1 WHERE logdate < TRUNC(sysdate,'d')
기록된 날짜(LOGDATE)가 일요일이 한번이라도 지났다면, 즉 이번주 일요일부터 토요일간의 기록이라면 그대로 두고 그 이상 오래된 경우 현재날짜(SYSDATE)를 LOGDATE에 남기는 쿼리

select ename,job,hiredate from emp where hiredate between '1981-02-20' and '1981-05-01';
--1981년02월20일부터 1985년05월01일까지의 레코드를 검색한다.(꼭옛날날짜에서최근날짜로검색)


select ename,(sysdate - hiredate)/7 week from emp;
--sysdate함수로 현재 날짜시간에서 입사날짜(hiredate)를 빼면 일수가나오고 거기서 7을 나누어

--근무한 주수를 알수있습니다.

select * from emp where hiredate='1980/12/17';
--날짜 비교는 ''을 이용하여 비교합니다.


select months_between(sysdate,hiredate)/12 ,hiredate from emp;
--오늘날짜에서 입사날짜를 빼서 달수를 구한후 12을 나누어 근무한 년수를 구할수있다.


select months_between(to_date(20011129,'yyyymmdd'),to_date(20020228,'yyyymmdd')) from dual;
--첫번째 날짜에서 두번째 날짜를 빼서 달수로 구한다.

select round(months_between(sysdate,hiredate)/12) ,hiredate from emp;
--소수점이 있는 결과에서 반올림합니다.

select trunc(months_between(sysdate,hiredate)/12) ,hiredate from emp;
--소수점이 있는 결과에서 버림합니다.


ADD_MONTHS 함수예제

SELECT ADD_MONTHS(HIREDATE,2) FROM EMP;
-- HIREDATE값에 2달를 더하여 출력

SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-1), 'YYYYMMDD'),
TO_CHAR(SYSDATE-30, 'HH24MIDD') FROM DUAL;
-- DATE형 현재 날짜시간에서 1달을 뺀후 출력

SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20060907230000','YYYYMMDDHH24MISS'),
-1),'YYYYMMDDHH24MI') FROM DUAL;
-- CHAR형 현재 날짜시간에서 1달을 뺀후 출력

select add_months(to_date('200706'||'01','yyyymmdd'),-1) from dual
-- 20070601에서 한달을 뺍니다.

select add_months(hiredate,-2) from emp;
--입사날짜에서 2달을 빼서 출력합니다.


select hiredate+100 from emp;
--입사날짜에서 100일을 더합니다.


select hiredate-100 from emp;
--입사날짜에서 100일을 뺍니다.


LAST_DAY() 함수
해당 날짜에 달에 마지막 일의 날짜를 출력한다.
사용예제
SELECT LAST_DAY('2006-05-05') FROM DUAL;
--2006-05-31

SELECT LAST_DAY(SYSDATE) FROM DUAL;
--2006-05-31 오후 10:35:51


※oracle에서는 날짜함수에(sysdate) 산술연산이 가능합니다.
1일->1
1시간->1/24
1분->1/24/60
1초->1/24/60/60

select sysdate-1 from dual;
--지금 시간 기준으로 1일전


select sysdate-(1/24) from dual;
--지금 시간 기준으로 1시간전


select sysdate+1/24/60*1 from dual;
--지금 시간 기주으로 1분전


select sysdate+1/24/60*10 from dual;
--지금 시간 기주으로 10분전


select to_date(200611210800,'yyyymmdd hh24miss')+ 10/24 from duaL;
--10시간을 더한다.


select to_char(to_date('2005-05-05'),'d') from account;
--날짜를 숫자형식의 요일로 출력(1-일요일,7-토요일)

select to_char(to_date('2005-05-05'),'day') from account;
--날짜를 알파벳요일로 출력

select to_char(to_date('2005-05-05'),'year') from account;
--날짜를 알파벳년도로 출력


select to_char(to_date('2005-05-05'),'month') from account;
-- 월을 영문으로 완벽하게 출력


select to_char(to_date('2005-05-05'),'mon') from account;
-- 월을 영문 앞 3글자만 출력


select decode(to_char(to_date('2005-05-05'),'d'),
'2','1',
'3','2',
'4','3',
'5','4',
'6','5',
'7','6',
'1','7') "요일"
from dual;

--날짜의 요일을 숫자로 출력(1-월요일,7-일요일)

DATE형 컬럼 비교시

SELECT * FROM TABLE_NAME WHERE FDATE < to_date('20070711','YYYYMMDD')

6. 프로그래밍 언어에서 날짜 검색시 방법

날짜 관련 컬럼은 DATE, CHAR(8), NCHAR(8)을 주지만 DATE는 7바이트이다.

DATE형은 아래와 같이 검색 조건을 사용한다.

WHERE A_DATE BETWEEN '2005-10-10' AND '2005-10-30';
WHERE A_DATE BETWEEN TO_DATE('2005-10-10') AND TO_DATE('2005-10-30');

CHAR(8), NCHAR(8)형은 아래와 같이 검색조건을 사용한다.

WHERE A_DATE BETWEEN '20051010' AND '20051030';

두가지의 장단점을 알아보자

7. 해당 시간이 현재 24시간이 지났는지 알수 있는 쿼리

SELECT CASE WHEN SYSDATE - TO_DATE('20070727','YYYYMMDD') >= 1
THEN 'Y' ELSE 'N' END RESUAL FROM DUAL;
※ SYSDATE가 날짜형이므로 빼주는 값도 날짜형이어야 합니다.

SELECT round(to_date('95/05/25'),'DAY')
FROM dual
1995/05/28 00:00:00
SELECT TRUNC(TO_DATE('95/05/25'), 'DAY')
FROM dual
1995/05/21 00:00:00

문제는 day 함수에 있습니다.
day함수는 요일을 나타내죠.
따라서 to_date('95/05/25')를 day로 표시하면 수요일이 나옵니다.
위에 쿼리는 그걸 반올림하였으니 그 주에 가장 큰 28일이 나왔구요,
아래 쿼리는 그걸 잘라내버렸으니 그 주에 가장 작은 21일이 나온 겁니다.

SELECT SYSDATE + 2/24 FROM DUAL;
-- 현재시간의 2시간후에 시간을 출력
SELECT SYSDATE - 2/24 FROM DUAL;
-- 현재시간의 2시간전의 시간을 출력

select to_char(trunc(sysdate), 'rrrr/mm/dd') A from dual;
select to_char(trunc(sysdate), 'yyyy/mm/dd') A from dual;
YYYY포맺은 현재를 기준으로 합니다.
RRRR기준은 .년도의 뒷자리를 기준으로
2000년도 기준으로 보면
0-49 년은 after year 35/12/12 ->2055/12/12
50-99 년은 before year 51/12/12 ->1951/12/12
가 됨니다.

8. 날짜 관련 함수

SYSDATE 함수
? 현재 시스템 날짜를 출력
SELECT SYSDATE FROM DUAL;
-- ORACLE 10g XE 에서 출력되는 날짜형식
-- 2008-05-17 오후 5:15:17

LAST_DAY 함수
? 해당 날짜의 달에서 마지막 일을 출력
SELECT LAST_DAY(SYSDATE) FROM DUAL;
--2008-05-31 오후 5:16:54

 

Posted by 1010
반응형

SQL - Timestamp
A timestamp servers as the catch all for dates and times. Retrieving a timestamp is very simple and the result can be converted or manipulated in nearly every way imaginable.


SQL Code:
SELECT CURRENT_TIMESTAMP;
Return a Timestamp:2004-06-22 10:33:11.840
Keep in mind that each platform of SQL (DB2, Oracle, SQL Server, etc...) may return dates and times which are formatted differently.
SQL- Date FunctionsAs we just mentioned, it is possible to breakdown timestamps into their individual pieces using any of the following date functions.

SQL Code:
SELECT MONTH(CURRENT_TIMESTAMP);
Return a Month:6 SQL Code:
SELECT DAY(CURRENT_TIMESTAMP);
Return a Day:22

There are many more functions available, including functions to extract milliseconds, names of the months, names of each week day, etc.
Each SQL platform varies in the actual naming of date functions. Here's a few c\The following is a list of other date functions available to most platforms of SQL with the exception of MS's SQL Server.

SQL Function Code:
SELECT DATE(CURRENT_TIMESTAMP); - returns a date (2004-06-22)
SELECT TIME(CURRENT_TIMESTAMP); - returns the time (10:33:11.840)
SELECT DAYOFWEEK(CURRENT_TIMESTAMP); - returns a numeric value (1-7)
SELECT DAYOFMONTH(CURRENT_TIMESTAMP); - returns a day of month (1-31)
SELECT DAYOFYEAR(CURRENT_TIMESTAMP); - returns the day of the year (1-365)
SELECT MONTHNAME(CURRENT_TIMESTAMP); - returns the month name (January - December
SELECT DAYNAME(CURRENT_TIMESTAMP); - returns the name of the day (Sunday - Saturday)
SELECT WEEK(CURRENT_TIMESTAMP); - returns number of the week (1-53)


Timestamps are often the easiest to work with, but we certainly are not limited to using only the current_timestamp as our parameter. We can send any date, time, or timestamp to the function which then returns our result.

SQL Code:
SELECT MONTHNAME('2004-11-27');
Return a Month Name: MONTHNAME('2004-11-27') November
Date functions can also be performed on table columns similarly to numeric and mathematical functions such as SUM() or AVG().

SQL Code:
SELECT DAYOFYEAR(column_name) FROM table_name WHERE name = 'Joe';
SQL will return a numeric result from 1 - 365 representing the day of the year that Joe's record was created/inserted.We can expand this concept one step further with the use of a subquery. Say we have a table with a column named timestamp. In this table column are timestamps of when each record was entered and we would like to know what was the numeric day of the year that a record was entered.

SQL Code:
SELECT DAYOFYEAR((SELECT DATE(timestamp) FROM employees WHERE name = 'James Bond'));
Above you can see how it is possible to combine several date functions as well as a subquery to return very specific information about Mr. James Bond.
SQL - Inserting Date DataDate data exists as numbers, strings, and timestamps. Built into most platforms are several date column types such as DATE or TIMESTAMP. By setting the default value to the current date or timestamp, the table column will automatically be filled with a current date/timestamp as each record is inserted.
Here's the code to add a timestamp column to an existing table.
SQL Code:
ALTER TABLE `orders` ADD `order_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Now each time an order is placed in our make believe business, a timestamp of that order is also recorded.A date or timestamp table column will only allow date data types to be inserted as values so be sure to convert any strings or numbers to dates and timestamps before trying to insert them.

SQL - Datepart()

Microsoft's SQL Server takes a little different approach to working with dates. It is still possible to extract individual parts of a timestamp and several other functions also work as outlined in SQL - Date. The difference is that SQL Server uses one main function as oppose to several different functions ie the DATEPART() function.
Datepart() requires two parameters, a part argument and a date argument. By part we mean year, day of the year, day of the week, etc. Let's look at an example.

SQL Code:
SELECT DATEPART(week, '2005-12-31');Return the Week Number:53

Here we have successfully pulled the "week number" from existing date.
SQL's CURRENT_DATE function could be also be substituted or a string value representing the year ('Dec 31, 2005').

Posted by 1010
반응형

–1시간 더하기

select to_char(to_date(’121212′,’hh24miss’)+1/24,’hh24:mi:ss’) from dual;

–30분 더하기

select to_char(to_date(’121212′,’hh24miss’)+30/24/60,’hh24:mi:ss’) from dual;

select to_char(to_date(’121212′,’hh24miss’)+30/(24*60),’hh24:mi:ss’) from dual;

–40초 더하기

select to_char(to_date(’121212′,’hh24miss’)+40/24/60/60,’hh24:mi:ss’) from dual;

select to_char(to_date(’121212′,’hh24miss’)+40/(24*60*60),’hh24:mi:ss’) from dual;

–12시간 58분 58초 더하기

select to_char(to_date(’121212′,’hh24miss’)+12/24 + 58/24/60 + 58/24/60/60,’hh24:mi:ss’) from dual;

– 시: 분: 초 가져오기

select substr(’125858′,1,2), substr(’125858′,3,2), substr(’125858′,5,2) from dual;

[참고] http://julymorning.co.kr/xe/index.php?document_srl=3798&mid=tiptech_prog

 

Posted by 1010
반응형
Posted by 1010
반응형

출처 : http://zsoo.net/68

 

1. Help -> Install New Software... 를 누릅니다


Add 버튼을 눌러 Location에 http://jadclipse.sf.net/update 을 적고 OK를 누릅니다.

밑 플러그인 목록에 JDT Decompiler Features를 체크 하여 설치합니다.

이클립스를 재시작합니다.



2. Window -> Preferences

General -> Editors -> File Associations 에서

*.class를 선택하고 밑에서 편집기를 Decompiled Class File Viewer를 선택하여 Default 로 지정합니다.



Java -> Decompilers 에서

Decompiler를 Jad를 선택합니다.



3. http://www.varaneckas.com/jad 에서 jad를 다운받습니다.


압축을 풀어 이클립스 실행파일이 있는 폴더에 복사합니다.



4. 이제 편집기에서 소스가 궁금한 클래스명을 선택하고 F3을 누르면..

디컴파일된 소스가 보이게 됩니다.. 클래스에 따라서.. 결과가 제대로 나오지 않을 수도있습니다..

참고로 실제 소스와 완전히 같지 않기 때문에 디버깅시에 전혀 엉뚱한 라인을 가리킵니다..ㄱ-

 

Posted by 1010
반응형
출처 : http://designblack.com/bbs/board.php?bo_table=tip&wr_id=307&sca=%C7%C3%B7%A1%BD%C3 

 

var activeNum = pageNum;
var activesub = subNum;
var overNum = activeNum;
var menuNum = 4;

var linkDim=new Array();
linkDim[0]="URL써주세요";
linkDim[1]="URL써주세요";
linkDim[2]="URL써주세요";
linkDim[3]="URL써주세요";
//////////////////////////
for (var i = 0; i<menuNum; i++) {
//몽 추가
this["menu"+i].bt.onRelease = function() {
this._parent._parent.overNum = this._parent._name.substring(4);
if (this._parent._parent.overNum==3) getURL(linkDim[this._parent._parent.overNum],"_blank");
else getURL(linkDim[this._parent._parent.overNum]);
//trace(i);
}
this["menu"+i].bt.onRollOver = function() {
this._parent._parent.overNum = this._parent._name.substring(4);
};
this["menu"+i].bt.onRollOut = function() {
this._parent._parent.overNum = this._parent._parent.activeNum;
};
this["menu"+i].onEnterFrame = function() {
if (this._parent.overNum == this._name.substring(4)) {
this.nextFrame();
this.flag = true;
} else {
this.flag = false;
this.prevFrame();
this.prevFrame();
}
};
}


무비클립의 이름은 menu0부터~ menuNum의 갯수만큼

 

Posted by 1010
반응형

 

출처 : http://slog2.egloos.com/3574039

1. log4j 다운.
- http://logging.apache.org/log4j/1.2/download.html 접속.
- apache-log4j-1.2.16.zip 을 다운받고 압축을 푼다.
- 압축을 푼 폴더안에 og4j-1.2.16.jar 파일이 있는지 확인 한다.

2. 이클립스 설정.
- 프로젝트 WEB_INF/lib 폴더에 log4j-1.2.16.jar 파일을 복사 붙여넣기 한다.
- 프로젝트 src에 new - file 만들기로 log4j.properties 파일을 만든다.
- log4j.properties 파일에 소스를 붙여넣기 한다.

log4j.rootLogger = debug, stdout, dailyfile //debug를 info,error,warn,fatal 로 조정만 하여 레벨 조정이 가능하다.
//콘솔창에 찍히는 부분 설정.

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d] - %m%n

//file에 기록되는 부분 설정.
log4j.appender.dailyfile.Threshold = DEBUG
log4j.appender.dailyfile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyfile.File = c:\\log\\logfile.log //여기에 지정된 폴더로 날짜별로 로그파일이 생성된다
log4j.appender.dailyfile.layout = org.apache.log4j.PatternLayout
log4j.appender.dailyfile.layout.ConversionPattern=%5p ({%t} %F[%M]:%L) [%d] - %m%n

3. 라이브러리 추가
- 프로젝트 우측클릭 properties 설정 - Java Build Path - Libraries - Add Libary... 클릭
- JUnit 클릭 - JUNIT library version : JUnit 3 - Finish

4. 사용해보기.
- log4j import
private static Logger logger = Logger.getLogger(TestLog4j.class);

- logger.debug("dddd");
logger.info("info");
logger.warn("warn");
logger.error("error");
logger.fatal("fatal");
요런식으로 찍어보면 된다.
찍힌 내용은 설정파일의 경로에 파일로도 저장된다.
설정파일의 debug를 warn이라고 해놓으면 info, debug의 메시지는 당연히 안찍힌다.
설정파일 한방으로 찍히고 안찍히고를 결정 지을 수 있다.

 

Posted by 1010