javascript - Bir tarih nesnesinden yıl/ay/gün nasıl alınır?


alert(dateObj) Wed Dec 30 2009 00:00:00 GMT+0800 verir

Tarihi 2009/12/30 formatında nasıl alabilirim?

Cevap #1

const dateObj = new Date();
const month   = dateObj.getUTCMonth() + 1; // months from 1-12
const day     = dateObj.getUTCDate();
const year    = dateObj.getUTCFullYear();

const newDate = year + "/" + month + "/" + day;

// Using template literals:
const newDate = `${year}/${month}/${day}`;

// Using padded values, so that 2023/1/7 becomes 2023/01/07
const pMonth        = month.toString().padStart(2,"0");
const pDay          = day.toString().padStart(2,"0");
const newPaddedDate = `${year}/${pMonth}/${pDay}`;

veya yeni bir tarih belirleyebilir ve yukarıdaki değerleri verebilirsiniz

Cevap #2

new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"

new Date().toLocaleString().split(',')[0]
"2/18/2016"

Cevap #3

var dt = new Date();

dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();

Ay indeksleri 0 tabanlı olduğu için, onu 1 artırmanız gerekir.

Düzenle

Tarih nesnesi fonksiyonlarının tam listesi için bkz

Tarih

getMonth()

Belirtilen tarihteki ayı (0-11) yerel saate göre döndürür.

getUTCMonth()

Belirtilen tarihteki ayı (0-11) evrensel zamana göre döndürür.

Cevap #4

Neden toISOString() yöntemini slice ile veya basitçe toLocaleDateString() ile kullanmıyorsunuz?

Dikkat edin, toISOString tarafından döndürülen saat dilimi her zaman sıfır UTC ofsetidir, oysa toLocaleDateString içinde kullanıcı aracısının saat dilimidir.

Buraya bak:

const d = new Date() // today, now

// Timezone zero UTC offset
console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD

// Timezone of User Agent
console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD
console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY

Cevap #5

2021 CEVAP

Yerleşik .toLocaleDateString() fonksiyonunu kullanabilirsiniz; bu fonksiyon, locale (MM/DD/YYYY veya YYYY/MM/DD gibi bir format seçmek için), timezone (tarihi dönüştürmek için) ve format detay seçeneklerini (örneğin: 1 vs 01 vs January) destekleyen birkaç yararlı parametreyi destekler.

Örnekler

console.log( new Date().toLocaleDateString() ); // 8/19/2020
    
console.log( new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}) ); // 08/19/2020 (month and day with two digits)

console.log( new Date().toLocaleDateString('en-ZA') ); // 2020/08/19 (year/month/day) notice the different locale
    
console.log( new Date().toLocaleDateString('en-CA') ); // 2020-08-19 (year-month-day) notice the different locale

console.log( new Date().toLocaleString("en-US", {timeZone: "America/New_York"}) ); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

console.log( new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}) );  // 09 (just the hour)

Bazen bir tarihi istediğiniz özel formatta yazdırmak için, o formatla uyumlu bir yerel ayar bulmanız gerektiğini unutmayın. Yerel ayar örneklerini şurada bulabilirsiniz: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

Lütfen locale sadece formatı değiştirdiğine dikkat edin, eğer belirli bir tarihi belirli bir ülke veya şehir saatine dönüştürmek istiyorsanız, o zaman timezone parametresini kullanmanız gerekir.

Cevap #6

Sana Moment.js kullanmanı öneririm http://momentjs.com/

O zaman şunu yapabilirsin:

moment(new Date()).format("YYYY/MM/DD");

Not: Mevcut TarihSaat'i almak istiyorsanız aslında new Date() eklemenize gerek yok, bunu sadece tarih nesnesi geçirebileceğinize bir referans olarak ekledim. Mevcut TarihSaat için bu da çalışır:

moment().format("YYYY/MM/DD");

Cevap #7

let dateObj = new Date();

let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());

Referans olarak aşağıdaki detayları görebilirsiniz

new Date().getDate()          // Return the day as a number (1-31)
new Date().getDay()           // Return the weekday as a number (0-6)
new Date().getFullYear()      // Return the four digit year (yyyy)
new Date().getHours()         // Return the hour (0-23)
new Date().getMilliseconds()  // Return the milliseconds (0-999)
new Date().getMinutes()       // Return the minutes (0-59)
new Date().getMonth()         // Return the month (0-11)
new Date().getSeconds()       // Return the seconds (0-59)
new Date().getTime()          // Return the time (milliseconds since January 1, 1970)

let dateObj = new Date();

let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());

console.log(myDate)

Cevap #8

bilgi

Eğer 2 basamaklı bir ay ve tarih isteniyorsa (2016/01/01 vs 2016/1/1)

kod

var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);

çıktı

2016/10/06

keman

https://jsfiddle.net/Hastig/1xuu7z7h/

kredi

Daha fazla bilgi ve kredi bu cevaptan

daha fazla

.slice hakkında daha fazla bilgi edinmek için w3schools'daki kendin dene editörü, onu nasıl kullanacağımı daha iyi anlamama yardımcı oldu.

Cevap #9

var date = new Date().toLocaleDateString()
"12/30/2009"

Cevap #10

Date get yöntemlerini kullanın.

http://www.tizag.com/javascriptT/javascriptdate.php

http://www.htmlgoodies.com/beyond/javascript/article.php/3470841

var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();

Cevap #11

Güzel biçimlendirme eklentisi: http://blog.stevenlevithan.com/archives/date-time-format.

Bununla şunu yazabilirsin:

var now = new Date();
now.format("yyyy/mm/dd");

İlgili makaleler