オブジェクトを呼び出すgetMonth()
と、が取得さgetDate()
れdate
ますsingle digit number
。例えば :
の場合january
、と表示されます1
が、と表示する必要があります01
。どうやってするか?
オブジェクトを呼び出すgetMonth()
と、が取得さgetDate()
れdate
ますsingle digit number
。例えば :
の場合january
、と表示されます1
が、と表示する必要があります01
。どうやってするか?
回答:
("0" + this.getDate()).slice(-2)
日付、および同様:
("0" + (this.getMonth() + 1)).slice(-2)
月間。
function addZ(n){return n<10? '0'+n:''+n;}
が、もう少し一般的です。
getMonth
およびgetDate
文字列ではなく数値を返します。そして文字列との互換性が必要な場合'0' + Number(n)
は、仕事をします。
「YYYY-MM-DDTHH:mm:ss」のような形式が必要な場合は、これがより高速になる可能性があります。
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
または、一般的に使用されるMySQL日時形式「YYYY-MM-DD HH:mm:ss」:
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
これが役に立てば幸い
月の例:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
このDate
ような関数でオブジェクトを拡張することもできます:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
これを行う最良の方法は、独自のシンプルなフォーマッターを作成することです(以下を参照)。
getDate()
(1-31から)月の日を
getMonth()
返します(0-11から)月を返します< 0ベース、0 = 1月、11 = 12月を
getFullYear()
返します(4桁)< 使用しませんgetYear()
function formatDateToString(date){
// 01, 02, 03, ... 29, 30, 31
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
// 01, 02, 03, ... 10, 11, 12
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
// 1970, 1971, ... 2015, 2016, ...
var yyyy = date.getFullYear();
// create the format you want
return (dd + "-" + MM + "-" + yyyy);
}
なぜ使用しないのpadStart
ですか?
var dt = new Date();
year = dt.getYear() + 1900;
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
これは、月または日が10未満の場合でも、常に2桁の数値を返します。
ノート:
getYear()
1900年から年を返し、必要としませんpadStart
。getMonth()
月を0〜11で返します。
getDate()
1から31までの日を返します。
07
ので、文字列をパディングする前に1を追加する必要はありません。以下は、3項演算子を使用してdb2日付形式、つまりYYYY-MM-DDを変換するために使用されます。
var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate;
alert(createdDateTo);
私はこれを行います:
var d = new Date('January 13, 2000');
var s = d.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
console.log(s); // prints 01/13/2000
それは私が得ることを探していたいくつかの時間を節約するかもしれない場合:
YYYYMMDD
今日のために、そしてうまくいった:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
DD/MM/YY
、私は行ったnew Date().toISOString().substr(0, 10).split('-').reverse().map(x => x.substr(0, 2)).join('/')
これは私の解決策でした:
function leadingZero(value) {
if (value < 10) {
return "0" + value.toString();
}
return value.toString();
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
答えではありませんが、変数に必要な日付形式を取得する方法を次に示します
function setDateZero(date){
return date < 10 ? '0' + date : date;
}
var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);
お役に立てれば!
MDNからのヒント:
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
new Date().getMonth()
メソッドは月を数値として返します(0-11)
この機能で簡単に正しい月番号を取得できます。
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
そして、こちらの別のバージョンhttps://jsfiddle.net/ivos/zcLxo8oy/1/、役立つことを願っています。
var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup
strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
ここでの回答は役に立ちましたが、デフォルトの名前には月、日、月、時間、秒だけでなく、それ以上のものが必要です。
興味深いことに、上記のすべてに「0」のプリペンドが必要でしたが、「+ 1」が必要なのは1か月だけで、それ以外は必要ありませんでした。
例として:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
私の解決策:
function addLeadingChars(string, nrOfChars, leadingChar) {
string = string + '';
return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}
使用法:
var
date = new Date(),
month = addLeadingChars(date.getMonth() + 1),
day = addLeadingChars(date.getDate());
jsfiddle:http ://jsfiddle.net/8xy4Q/1/
var net = require('net')
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
function now () {
var d = new Date()
return d.getFullYear() + '-'
+ zeroFill(d.getMonth() + 1) + '-'
+ zeroFill(d.getDate()) + ' '
+ zeroFill(d.getHours()) + ':'
+ zeroFill(d.getMinutes())
}
var server = net.createServer(function (socket) {
socket.end(now() + '\n')
})
server.listen(Number(process.argv[2]))
getDate()関数で日付を1ではなく01として返す場合は、次のコードを使用します。今日の日付が01-11-2018であると仮定しましょう
var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();
console.log(today); //Output: 2018-11-1
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today); //Output: 2018-11-01
私はこのようなことをしたかった、そしてこれは私がやったことです
PS私は正しい答えが上にあることを知っていますが、ここに自分のものを追加したかっただけです
const todayIs = async () =>{
const now = new Date();
var today = now.getFullYear()+'-';
if(now.getMonth() < 10)
today += '0'+now.getMonth()+'-';
else
today += now.getMonth()+'-';
if(now.getDay() < 10)
today += '0'+now.getDay();
else
today += now.getDay();
return today;
}
currentDate(){
var today = new Date();
var dateTime = today.getFullYear()+'-'+
((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
(today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
(today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
(today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
(today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());
return dateTime;
},
Moment https://momentjs.com/と呼ばれる別のライブラリを使用することをお勧めします
このようにして、余分な作業を行うことなく、日付を直接フォーマットできます。
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
それを使用できるように、モーメントもインポートするようにしてください。
yarn add moment
# to add the dependency
import moment from 'moment'
// import this at the top of the file you want to use it in
これが役に立てば幸い:D
$("body").delegate("select[name='package_title']", "change", function() {
var price = $(this).find(':selected').attr('data-price');
var dadaday = $(this).find(':selected').attr('data-days');
var today = new Date();
var endDate = new Date();
endDate.setDate(today.getDate()+parseInt(dadaday));
var day = ("0" + endDate.getDate()).slice(-2)
var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
var year = endDate.getFullYear();
var someFormattedDate = year+'-'+month+'-'+day;
$('#price_id').val(price);
$('#date_id').val(someFormattedDate);
});