현재 Page에서 열기

var OpenURL = 'https://openurl.co.kr';

window.location = OpenURL;

새탭에서 Page 열기

var OpenURL = 'https://openurl.co.kr';

window.open(OpenURL);

<a>~</a> 태그의 속성

_blank: 새 탭, 창

_self: 현재 탭, 창

_parent: 부모 탭, 창
_top: 최상위 탭, 창

<a href="http://tistory.com/" target="_blank">새 창, 탭 열기</a>
<a href="http://tistory.com/" target="_self">현재 창, 탭 열기</a>
<a href="http://tistory.com/" target="_parent">부모 탭, 창</a>
<a href="http://tistory.com/" target="_top">최상위 탭, 창</a>

기능

1. Chart.js 2.x 버전 Pie Chart

2. 파이 차트 클릭 이벤트 ( Pie Chart Click Event ) - label 및 value 조회

3. 마우스 오버없이 레이블을 항상 백분율(%)값을 표시

 

html

* chart를 그리기 위한 canvas를 생성

* 다른 로직에서 canvas를 참고하기 위해 id를 지정 ( 예제는 cPieChart 으로 생성 )

<canvas id="cPieChart" style="min-height: 500px; height: 500px; max-height: 1000px; width: 700px; max-width: 100%;"></canvas>

javascript

* chart.js를 사용하기 위해 Chart.min.js 를 추가

* 마우스 오버없이 레이블을 항상 표시하기 위한 chartjs-plugin-datalabels@0.7.0 추가

 

* config의 data -> datasets -> datalabels 부분에 설정값을 지정

   align : 레이블 위치

   backgroundColor : ctx 정보를 가져와서 value가 0 이상인 경우만 출력

   color : ctx 정보를 가져와서 value가 0 이상인 경우만 출력

   formatter : value, ctx 정보를 가져와서 0 이상인 경우 백분율값을 구하여 리턴

 

* Pie Chart 생성 후 onClick Event 값을 가져와서 이벤트 처리

  getElementsAtEvent(evt) 함수로 클릭 이벤트 값을 조회

  activePoints[0]["_index"] 로 클릭한 차트의 위치값을 조회

   >> 만약 하나의 canvas에 여러개의 chart가 있는 경우 아래 형태로 조회

        activePoints[0]["_index"]

        activePoints[1]["_index"]

        activePoints[2]["_index"]

 

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>

// Pie Chart ctx Get
var PieChart_ctx = document.getElementById('cPieChart').getContext('2d');

// Pie Chart Config Set
PieChart_config = {
    type: 'pie',
    data: {
        labels: ['OPEN', 'PROGRESSING', 'COMPLETE'],
        data: [13,11,14],
        datasets: [{
            label: 'Pie Chart Count',
            backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(75, 192, 192, 0.2)'
                        ],
            borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(75, 192, 192, 1)'
                        ],
            borderWidth: 1,
            datalabels: {
                labels: {
                    value: {
                        borderWidth: 2,
                        borderRadius: 4,
                        font: {size: 15},
                        formatter: function(value, ctx) {
                            var value = ctx.dataset.data[ctx.dataIndex];
                            return value > 0 ? Math.round(value / (ctx.dataset.data[0] + ctx.dataset.data[1] + ctx.dataset.data[2]) * 100) + ' %' : null;
                        },
                        color: function(ctx) {
                            var value = ctx.dataset.data[ctx.dataIndex];
                            return value > 0 ? 'white' : null;
                        },
                        backgroundColor:function(ctx) {
                            var value = ctx.dataset.data[ctx.dataIndex];
                            return value > 0 ? 'gray' : null;
                        },
                        padding: 4
                    }
                }
            }
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio : false,
        animation: false,
        legend: {
            position: 'left',
            display: true
        },
        title: {
            display: false,
            text: 'Pie Chart - Count',
            font: {
                size: 50
            },
            fontstyle: 'bold',
            position: 'top'
        }, 
        plugins: {
            legend: {
                position: 'left',
            },
            title: {
                display: true,
                text: 'Pie Chart - Count',
                font: { 
                    size: 25
                }
            }
        }
    }
};


// Pie Chart Create
var PieChart = new Chart(PieChart_ctx, PieChart_config);

// Pie Chart Event Set
document.getElementById("cPieChart").onclick = function(evt) {

    var activePoints = PieChart.getElementsAtEvent(evt);

    if(activePoints.length > 0)
    {
        //get the internal index of slice in pie chart
        var clickedElementindex = activePoints[0]["_index"];

        //get specific label by index 
        var label = PieChart.data.labels[clickedElementindex];

        //get value by index      
        var value = PieChart.data.datasets[0].data[clickedElementindex];

        // label and value Process
        
   }
};

참고

https://stackoverflow.com/questions/26257268/click-events-on-pie-charts-in-chart-js

https://chartjs-plugin-datalabels.netlify.app/samples/charts/line.html

https://chartjs-plugin-datalabels.netlify.app/samples/advanced/multiple-labels.html

 

Multiple Labels | chartjs-plugin-datalabels

Multiple Labels Use multiple labels configuration to display 3 labels per data, one for the index, one for the label and one for the value. Move the mouse over the chart to display label ids. { type: 'doughnut', data: { labels: labels, datasets: [{ backgro

chartjs-plugin-datalabels.netlify.app

 

html

<table id="example" class="stripe" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            
            ............
            
            <tr>
                <td>Donna Snider</td>
                <td>Customer Support</td>
                <td>New York</td>
                <td>27</td>
                <td>2011/01/25</td>
                <td>$112,000</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>

javascript

$(document).ready(function() {
    $('#example').DataTable();
} );

In addition to the above code, the following Javascript library files are loaded for use in this example:

https://code.jquery.com/jquery-3.5.1.js
https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js

css

The following CSS library files are loaded for use in this example to provide the styling of the table:

https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css

참고

https://datatables.net/examples/styling/stripe.html

 

DataTables example - Base style - stripe

Base style - stripe This example shows DataTables with just the stripe class specified. Name Position Office Age Start date Salary Tiger Nixon System Architect Edinburgh 61 2011/04/25 $320,800 Garrett Winters Accountant Tokyo 63 2011/07/25 $170,750 Ashton

datatables.net

javascript

var json = { 'NAME':'홍길동', 'SEX':'남', 'AGE':'99세'};

for(key in json) {
    alert('key:' + key + ' / ' + 'value:' + json[key]);
}

jquery

var json = { 'NAME':'홍길동', 'SEX':'남', 'AGE':'99세'}; 

$.each(json, function(key, value){
    alert('key:' + key + ' / ' + 'value:' + value);
});

참고

https://gent.tistory.com/17

 

[javascript|자바스크립트] foreach 구문을 이용하여 JSON 값 쉽게 가져오기 (json key get value)

자바스크립트의 foreach 구문을 이용하여 JSON 객체의 키(key)와 값(value)를 쉽게 가져올 수 있다. jQuery를 사용한다면 $.each 구문을 대신 사용할 수도 있다. ■ Javascript var json = { 'NAME':'홍길동', 'S..

gent.tistory.com

html의 td style 부분에 아래 내용을 추가

{ white-space:pre-line , word-break: break-all}

<table id="test_table">
  <thead>
    <tr>
      <th style="text-align:center;">ID</th>
      <th style="text-align:center;">Info Detail</th>
      <th style="text-align:center;">Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> 1 </td>
      <td style="white-space:pre-line;word-break: break-all;">
        Info 1
        Info 2
        Value 1
        Value 2
      </td>
      <td>'2021-07-10 09:00:00' 
      </td>
    </tr>
  </tbody>
  <tfoot>
  </tfoot>
</table>

참고

https://stackoverflow.com/questions/10937218/how-to-show-multiline-text-in-a-table-cell

 

How to show multiline text in a table cell

I want to show a paragraph from database into a table cell. The result is a large 1 line, ignoring how its organised in database. ignoring 'enters' for example (new lines) I want to show it exactly

stackoverflow.com

1. 테이블 행(row) 클릭 시 해당 행의 값을 가져오기

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
    <!-- jQuery  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- bootstrap JS -->
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>   
    <!-- bootstrap CSS -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
 
<body>  
    <br><br>
    <div class="row">
        <table id="example-table-1" width="100%" class="table table-bordered table-hover text-center">
            <thead>
                <tr>
                    <th>No. </th>
                    <th>아이디</th>
                    <th>이름</th>
                    <th>이메일</th>
                </tr>
            </thead>
            <tbody>                
                <tr>
                    <td>1</td>
                    <td>user01</td>
                    <td>홍길동</td>
                    <td>hong@gmail.com</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>user02</td>
                    <td>김사부</td>
                    <td>kim@naver.com</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>user03</td>
                    <td>존</td>
                    <td>John@gmail.com</td>
                </tr>
            </tbody>
        </table>
        <div class="col-lg-12" id="ex1_Result1" ></div> 
        <div class="col-lg-12" id="ex1_Result2" ></div> 
    </div>
    <br><br>     
</body>
</html>

javascript

<script>
    // 테이블의 Row 클릭시 값 가져오기
    $("#example-table-1 tr").click(function(){     
        var str = ""
        var tdArr = new Array();    // 배열 선언
            
        // 현재 클릭된 Row(<tr>)
        var tr = $(this);
        var td = tr.children();
            
        // tr.text()는 클릭된 Row 즉 tr에 있는 모든 값을 가져온다.
        console.log("클릭한 Row의 모든 데이터 : "+tr.text());
            
        // 반복문을 이용해서 배열에 값을 담아 사용할 수 도 있다.
        td.each(function(i){
            tdArr.push(td.eq(i).text());
        });
            
        console.log("배열에 담긴 값 : "+tdArr);
            
        // td.eq(index)를 통해 값을 가져올 수도 있다.
        var no = td.eq(0).text();
        var userid = td.eq(1).text();
        var name = td.eq(2).text();
        var email = td.eq(3).text();
            
            
        str += " * 클릭된 Row의 td값 = No. : <font color='red'>" + no + "</font>" +
               ", 아이디 : <font color='red'>" + userid + "</font>" +
               ", 이름 : <font color='red'>" + name + "</font>" +
               ", 이메일 : <font color='red'>" + email + "</font>";        
          
        $("#ex1_Result1").html(" * 클릭한 Row의 모든 데이터 = " + tr.text());        
        $("#ex1_Result2").html(str);
    });    
</script>

2. 버튼 클릭 시 해당 행(row)의 값을 가져오기

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- jQuery  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
    <!-- bootstrap JS -->
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <!-- bootstrap CSS -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> 
</head>
 
<body>   
    <br><br>
    <div class="row">
        <table id="example-table-2" width="100%" class="table table-bordered table-hover text-center">
            <thead>
                <tr>
                    <th>No. </th>
                    <th>아이디</th>
                    <th>이름</th>
                    <th>이메일</th>
                    <th>버튼</th>
                </tr>
            </thead>
            <tbody>                
                <tr>
                    <td>1</td>
                    <td>user04</td>
                    <td>맥크리</td>
                    <td>sunset@gmail.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>user05</td>
                    <td>메르시</td>
                    <td>Mercy@naver.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>user06</td>
                    <td>한조</td>
                    <td>trolling@gmail.com</td>
                    <td><input type="button" class="checkBtn" value="클릭" /></td>
                </tr>
            </tbody>
        </table>
        <div class="col-lg-12" id="ex2_Result1" ></div> 
        <div class="col-lg-12" id="ex2_Result2" ></div> 
    </div> 
    <br><br> 
</body>
</html>

javascript

<script>
    // 버튼 클릭시 Row 값 가져오기
    $(".checkBtn").click(function(){ 
            
        var str = ""
        var tdArr = new Array();    // 배열 선언
        var checkBtn = $(this);
            
        // checkBtn.parent() : checkBtn의 부모는 <td>이다.
        // checkBtn.parent().parent() : <td>의 부모이므로 <tr>이다.
        var tr = checkBtn.parent().parent();
        var td = tr.children();
            
        console.log("클릭한 Row의 모든 데이터 : "+tr.text());
            
        var no = td.eq(0).text();
        var userid = td.eq(1).text();
        var name = td.eq(2).text();
        var email = td.eq(3).text();
            
            
        // 반복문을 이용해서 배열에 값을 담아 사용할 수 도 있다.
        td.each(function(i){    
            tdArr.push(td.eq(i).text());
        });
            
        console.log("배열에 담긴 값 : "+tdArr);
            
 
        str += " * 클릭된 Row의 td값 = No. : <font color='red'>" + no + "</font>" +
               ", 아이디 : <font color='red'>" + userid + "</font>" +
               ", 이름 : <font color='red'>" + name + "</font>" +
               ", 이메일 : <font color='red'>" + email + "</font>";        
            
        $("#ex2_Result1").html(" * 클릭한 Row의 모든 데이터 = " + tr.text());        
        $("#ex2_Result2").html(str);    
    }); 
</script>

참고

https://all-record.tistory.com/172

html에서 select2 id값을 설정

javascript에서 id값으로 html의 select2 값을 조회 및 변경

<!DOCTYPE html>
<html>
  <head>
    <title>Select2 Test</title>
    <!-- select2 css cdn -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/css/select2.min.css" rel="stylesheet" />
  </head>
  <body>
    <br />
    <div style="margin-left:10px;">
      <select class="form-control select2" id="search_type" name="search_type">
        <option value="all">ALL</option>
        <option value="sql">SQL</option>
        <option value="os">OS</option>
      </select>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <!-- select2 javascript cdn -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/js/select2.min.js"></script>
    <script>
    
      //Initialize Select2 Elements
      $('.select2').select2({
        theme: "bootstrap4",
        width: 'auto',
        dropdownAutoWidth: true
      })
      
      //select2 선택값 변경
      $('#search_type').val('OS');
      // 위 코드로 변경이 되지 않는 경우
      $('#search_type').val('OS').trigger('change');
       
    </script>
  </body>
</html>

Python flask

test edit : db 데이터 수정 이후, 실행 결과를 리턴

test list : db의 table 조회 이후, 여러 행을 리스트 형태로 리턴

test detail : db 데이터 조회 결과가 1건인 경우, json 형태로 리턴

from flask import render_template, request, flash, redirect, url_for, Blueprint, Markup, jsonify, session, make_response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text, update
from sqlalchemy.exc import SQLAlchemyError

@bts_blueprint.route('test/edit', methods=['POST'])
def test_edit():

    print("## test_edit ##")

    try:
        # 처리 변수
        numId = request.form['id']
        strName = request.form['name']

        # 처리 로직
        sql = text('update tblTest set name = :strName where id = :numId')
        connection = db.session.connection()
        db.engine.execute(sql, numId=numId, strName=strName)
                
        return jsonify(message="Edit Success"), 200

    except (RuntimeError, TypeError, NameError, SQLAlchemyError) as e:
        print("#### Edit Failed !! " + str(e))
        db.session.rollback()

        return jsonify(message=str(e)), 1000
        
        
@bts_blueprint.route('test/list', methods=['POST'])
def test_list():

    print("## test_list ##")

    # 처리 변수
    numId = request.form['id']

    # 처리 로직
    sql = text('select a, b, c, d, e from tblTest where id > :numId')
    connection = db.session.connection()
    results = db.engine.execute(sql, numId=numId)
                
    return render_template('test.html', results=list(results))


@bts_blueprint.route('test/detail', methods=['POST'])
def test_detail():

    print("## test_detail ##")

    # 처리 변수
    numId = request.form['id']

    # 처리 로직
    sql = text('select a, b, c from tblTest where id = :numId')
    connection = db.session.connection()
    results = db.engine.execute(sql, numId=numId)

    if results != None:
        results_detail = {}
        for r in results:
            results_detail['a'] = r[0]
            results_detail['b'] = r[1]
            results_detail['c'] = r[2]
            
    return jsonify(results_detail=results_detail)

javascript

funtion test_edit()
{
    // Test edit
    $.ajax({
        url:'/test/edit',
        type:'POST',
        data: {id:id, name:name},
        success: function(data){
            //Success
            showAlert('Edit Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('Edit Fail...','', 4, 3000);
        }
    });
}


funtion test_list()
{
    // Test list
    $.ajax({
        url:'/test/list',
        type:'POST',
        data: {id:id},
        success: function(data){
            //Success
            for(var key in data){
                console.log(key, data[key]);
            }
            
            showAlert('detail Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('list Fail...','', 4, 3000);
        }
    });
}


funtion test_detail()
{
    // Test detail
    $.ajax({
        url:'/test/detail',
        type:'POST',
        data: {id:id},
        success: function(data){
            //Success
            detail_a = data.results_detail.a
            detail_b = data.results_detail.b
            detail_c = data.results_detail.c
            
            showAlert('detail Successful!!!', '', 2, 2000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            var err_msg = JSON.parse(xhr.responseText);

            if (thrownError == 'UNKNOWN'){
                fail_msg = err_msg.message + ' (' + xhr.status + ')'
            } else {
                fail_msg = err_msg.message + ' (' + thrownError + ',' + xhr.status + ')';
            }
            showAlert('detail Fail...','', 4, 3000);
        }
    });
}

올해 01월 01일, 올해 12월 마지막일

//현재 시간
> var Nowdate = new Date()
> Nowdate 
Tue Jul 06 2021 23:36:20 GMT+0900 (한국 표준시)
//현재 년도
> FullYear = Nowdate.getFullYear()
2021
//현재 달
> Tmp_Month = Nowdate.getMonth()+1
7
> CurrentMonth = Tmp_Month >= 10 ? Tmp_Month : '0' + Tmp_Month
"07"
//마지막 달의 마지막 일
> (new Date(FullYear, 12, 0))
Fri Dec 31 2021 00:00:00 GMT+0900 (한국 표준시)
> (new Date(FullYear, 12, 0)).getDate()
31
// 올해 01월 01일
> FullYear + '-01-01 00:00:00'
"2021-01-01 00:00:00"
// 올해 12월 마지막일
> FullYear + '-12-' + LastDay + ' 23:59:59'
"2021-12-31 23:59:59"

일주일전

> var Nowdate = new Date()
> Nowdate
Tue Jul 06 2021 23:55:01 GMT+0900 (한국 표준시)
> var Agodate = new Date(Nowdate.getTime() - (7*24*60*60*1000))
//일주일전
> Agodate 
Tue Jun 29 2021 23:55:01 GMT+0900 (한국 표준시)

//현재 달
> var NowMonth = ((Nowdate.getMonth()+1) >= 10 ? (Nowdate.getMonth()+1) : '0' + (Nowdate.getMonth()+1))
"07"
//현재 일
> var NowDay = (Nowdate.getDate() >= 10 ? Nowdate.getDate() : '0' + Nowdate.getDate())
"06"
// 일주일전 달
> var AgoMonth = ((Agodate.getMonth()+1) >= 10 ? (Agodate.getMonth()+1) : '0' + (Agodate.getMonth()+1))
"06"
// 일주일전 일
> var AgoDay = (Agodate.getDate() >= 10 ? Agodate.getDate() : '0' + Agodate.getDate())
29

//현재 날짜
> Nowdate.getFullYear() + '-' + NowMonth + '-' + NowDay + ' 00:00:00'
"2021-07-06 00:00:00"

//일주일전 날짜
> Agodate.getFullYear() + '-' + AgoMonth + '-' + AgoDay + ' 00:00:00'
"2021-06-29 00:00:00"

1일 추가, 1시간 추가

//1일 추가
> tmpdate = new Date(2021,07,07)
Sat Aug 07 2021 00:00:00 GMT+0900 (한국 표준시)
> tmpdate.setTime(tmpdate.getTime() + (24*60*60*1000))
1628348400000
> new Date(tmpdate)
Sun Aug 08 2021 00:00:00 GMT+0900 (한국 표준시)

//1시간 추가
> tmpdate = new Date(2021,07,07)
Sat Aug 07 2021 00:00:00 GMT+0900 (한국 표준시)
> tmpdate.setTime(tmpdate.getTime() + (1*60*60*1000))
1628265600000
> new Date(tmpdate)
Sat Aug 07 2021 01:00:00 GMT+0900 (한국 표준시)

포멧 변경

function sDateToDate(strDate)
{
    //Ex) '04/26/2021 4:37 PM'
    var yyyyMMDD = String(strDate)
    var sYear = yyyyMMDD.substring(6,10);
    var sMonth = yyyyMMDD.substring(0,2);
    var sDate = yyyyMMDD.substring(3,5);
    var sTime = yyyyMMDD.substring(10,19);

    //Ex) '2021-04-26 4:37 PM'
    return sYear + '-' + sMonth + '-' + sDate + sTime
}

to Top