Khi chúng ta gọi getMonth()và getDate()vào dateđối tượng, chúng ta sẽ nhận được single digit number. Ví dụ :
Đối với january, nó hiển thị 1, nhưng tôi cần hiển thị nó như 01. Làm thế nào để làm điều đó?
Khi chúng ta gọi getMonth()và getDate()vào dateđối tượng, chúng ta sẽ nhận được single digit number. Ví dụ :
Đối với january, nó hiển thị 1, nhưng tôi cần hiển thị nó như 01. Làm thế nào để làm điều đó?
Câu trả lời:
("0" + this.getDate()).slice(-2)
cho ngày và tương tự:
("0" + (this.getMonth() + 1)).slice(-2)
trong tháng
function addZ(n){return n<10? '0'+n:''+n;}chung chung hơn một chút.
getMonthvà getDatetrả về số, không phải chuỗi. Và nếu khả năng tương thích với String là bắt buộc, thì '0' + Number(n)sẽ thực hiện công việc.
Nếu bạn muốn một định dạng như "YYYY-MM-DDTHH: mm: ss", thì điều này có thể nhanh hơn:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Hoặc định dạng datetime MySQL thường được sử dụng "YYYY-MM-DD HH: mm: ss":
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
Tôi hi vọng cái này giúp được
Ví dụ cho tháng:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
Bạn cũng có thể mở rộng Dateđối tượng với chức năng như vậy:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
Cách tốt nhất để làm điều này là tạo trình định dạng đơn giản của riêng bạn (như bên dưới):
getDate()trả về ngày trong tháng (từ 1-31)
getMonth()trả về tháng (từ 0-11) < dựa trên 0, 0 = tháng 1, 11 = tháng 12
getFullYear() trả về năm (bốn chữ số) < không sử dụnggetYear()
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);
}
Tại sao không sử dụng 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);
Điều này sẽ luôn trả về 2 chữ số ngay cả khi tháng hoặc ngày nhỏ hơn 10.
Ghi chú:
getYear()trả lại năm từ 1900 và không yêu cầu padStart.getMonth() trả về tháng từ 0 đến 11.
getDate() trả lại ngày từ 1 đến 31.
07và vì vậy chúng ta không cần thêm 1 trước khi đệm chuỗi.padStartkhông hoạt động với IE
Sau đây được sử dụng để chuyển đổi định dạng ngày db2, tức là YYYY-MM-DD bằng cách sử dụng toán tử ternary
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);
Tôi sẽ làm điều này:
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
Chỉ là một ví dụ khác, gần như một lớp lót.
var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
Nếu nó có thể dành chút thời gian tôi sẽ tìm cách để có được:
YYYYMMDD
cho ngày hôm nay, và đã cùng với:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
DD/MM/YY, tôi đã đếnnew Date().toISOString().substr(0, 10).split('-').reverse().map(x => x.substr(0, 2)).join('/')
Đây là giải pháp của tôi:
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;
Sử dụng Moment.js có thể được thực hiện như thế:
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
Không phải là một câu trả lời nhưng đây là cách tôi có được định dạng ngày tôi yêu cầu trong một biến
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);
Hi vọng điêu nay co ich!
Mẹo từ 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() phương thức trả về tháng dưới dạng số (0-11)
Bạn có thể dễ dàng nhận được số tháng chính xác với chức năng này.
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];
}
Và một phiên bản khác tại đây https://jsfiddle.net/ivos/zcLxo8oy/1/ , hy vọng sẽ hữu ích.
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")
Các câu trả lời ở đây rất hữu ích, tuy nhiên tôi cần nhiều hơn thế: không chỉ tháng, ngày, tháng, giờ & giây, cho một tên mặc định.
Thật thú vị, mặc dù trả trước "0" là cần thiết cho tất cả các bên trên, "+ 1" chỉ cần thiết cho tháng, không phải cho những người khác.
Ví dụ như:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
Giải pháp của tôi:
function addLeadingChars(string, nrOfChars, leadingChar) {
string = string + '';
return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}
Sử dụng:
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]))
nếu bạn muốn hàm getDate () trả về ngày là 01 thay vì 1, đây là mã cho nó .... Hãy giả sử ngày hôm nay là ngày 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
Tôi muốn làm một cái gì đó như thế này và đây là những gì tôi đã làm
ps tôi biết có câu trả lời đúng trên đầu, nhưng chỉ muốn thêm một cái gì đó của riêng tôi ở đây
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;
}
Nếu bạn kiểm tra nhỏ hơn 10 , bạn sẽ không tạo ra một chức năng mới cho điều đó. Chỉ cần gán một biến vào ngoặc và trả về nó với toán tử ternary.
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
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;
},
Tôi sẽ đề nghị bạn sử dụng một thư viện khác có tên là Moment https://momentjs.com/
Bằng cách này, bạn có thể định dạng ngày trực tiếp mà không phải làm thêm
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
Hãy chắc chắn rằng bạn cũng nhập thời điểm để có thể sử dụng nó.
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
Hy vọng điều này sẽ giúp: 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);
});