How do I get current date in JavaScript?
转载于:https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript
Use new Date()
to generate a new Date
object containing the current date and time.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write(today);
This will give you today's date in the format of mm/dd/yyyy.
Simply change today = mm +'/'+ dd +'/'+ yyyy;
to whatever format you wish.
</div>
UPDATED!, Scroll Down
If you want something simple pretty to the end user ... Also, fixed a small suffix issue in the first version below. Now properly returns suffix.
var objToday = new Date(),
weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
dayOfWeek = weekday[objToday.getDay()],
domEnder = function() { var a = objToday; if (/1/.test(parseInt((a + "").charAt(0)))) return "th"; a = parseInt((a + "").charAt(1)); return 1 == a ? "st" : 2 == a ? "nd" : 3 == a ? "rd" : "th" }(),
dayOfMonth = today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
curMonth = months[objToday.getMonth()],
curYear = objToday.getFullYear(),
curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;
document.getElementsByTagName('h1')[0].textContent = today;
<h1></h1>
UBBER UPDATE After much procrastination, I've finally GitHubbed and updated this with the final solution I've been using for myself. It's even had some last minute edits to make it sweeter! If you're looking for the old jsFiddle, please see this.
This update comes in 2 flavors, still relatively small, though not as small as my above, original answer. If you want extremely small, go with that.
Also Note: This is still less bloated than moment.js. While moment.js is nice, imo, it has to many secular methods, which require learning moment as if it were a language. Mine here uses the same common format as PHP:date.
Flavor 1
new Date().format(String)
My Personal Fav. I know the taboo, but works great on the Date Object. Just be aware of any other mods you may have to the Date Object.
// use as simple as
new Date().format('m-d-Y h:i:s'); // 07-06-2016 06:38:34
Flavor 2
dateFormat(Date, String)
More traditional all-in-one method. Has all the ability of the previous, but is called via method with Date param.
// use as simple as
dateFormat(new Date(), 'm-d-Y h:i:s'); // 07-06-2016 06:38:34
BONUS Flavor (requires jQuery)
$.date(Date, String)
This contains much more than just a simpleformat
option. It extends the base Date object and includes methods such asaddDays
. For more information, please see the Git.
In this mod, the format characters are inspired by PHP:date. For a complete list, please see my README
This mod also has a much longer list of pre-made formats. To use a premade format, simply enter its key name. dateFormat(new Date(), 'pretty-a');
As you may notice, you can use double \
to escape a character.
</div>
Try this:
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
The result will be like
15/2/2012
</div>
You can use Date.js library which extens Date object, thus you can have .today() method.
If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out momentjs. Terrific library - and only 5KB. http://momentjs.com/
You can use this
<script>
function my_curr_date() {
var currentDate = new Date()
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var my_date = month+"-"+day+"-"+year;
document.getElementById("dateField").value=my_date;
}
</script>
The HTML is
<body onload='return my_curr_date();'>
<input type='text' name='dateField' id='dateField' value='' />
</body>
var d = (new Date()).toString().split(' ').splice(1,3).join(' ');
document.write(d)
To break it down into steps:
(new Date()).toString()
gives "Fri Jun 28 2013 15:30:18 GMT-0700 (PDT)"
(new Date()).toString().split(' ')
divides the above string on each space and returns an array as follows: ["Fri", "Jun", "28", "2013", "15:31:14", "GMT-0700", "(PDT)"]
(new Date()).toString().split(' ').splice(1,3).join(' ')
takes the second, third and fourth values from the above array, joins them with spaces, and returns a string "Jun 28 2013"
</div>
var utc = new Date().toJSON().slice(0,10).replace(/-/g,'/');
document.write(utc);
Use the replace
option if you're going to reuse the utc
variable, such as new Date(utc)
, as Firefox and Safari don't recognize a date with dashes.
</div>
This works every time:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
document.write(today);
</div>
var date = new Date().toLocaleDateString("en-US");
Also, you can call method toLocaleDateString
with two parameters:
var date = new Date().toLocaleDateString("en-US", {
"year": "numeric",
"month": "numeric"
});
You can use moment.js: http://momentjs.com/
var m = moment().format("DD/MM/YYYY");
document.write(m);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
</div>
If you just want a date without time info, use:
var today = new Date();
today.setHours(0, 0, 0, 0);
document.write(today);
</div>
I think this is an old question but the easiest way would be the following:
var date = new Date();
var TimeStamp = date.toLocaleString();
function CurrentTime(){
alert(TimeStamp);
}
This will grab the current time, pass it to a string based on location and then you can call the function CurrentTime to display the time. This would be, to me, the most effective way to get a time stamp for something.
var dateTimeToday = new Date();
var dateToday = new Date(
dateTimeToday.getFullYear(),
(dateTimeToday.getMonth() + 1) /*Jan = 0! */,
dateTimeToday.getDate(),
0,
0,
0,
0);
You can get the current date call the static method now like this:
var now = Date.now()
reference:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/now
If you want a simple DD/MM/YYYY
format, I've just come up with this simple solution, although it doesn't prefix missing zeros.
var d = new Date();
document.write( [d.getDate(), d.getMonth()+1, d.getFullYear()].join('/') );
</div>
Varun's answer does not account for TimezoneOffset. Here is a version that does:
var d = new Date()
new Date(d.getTime() - d.getTimezoneOffset() * 60000).toJSON().slice(0, 10) // 2015-08-11
The TimezoneOffset
is minutes, while the Date constructor takes milliseconds, thus the multiplication by 60000
.
You can checkout this
var today = new Date();
today = parseInt(today.getMonth()+1)+'/'+today.getDate()+'/'+today.getFullYear()+"\nTime : "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds();
document.write(today);
And see the documentation for Date() constructor. link
I don't know if it will help anyone, but I'm using this to get today Date object.
new Date( 3600000*Math.floor(Date.now()/3600000) )
new Date().toISOString().slice(0,10);
would work too
What's the big deal with this.. The cleanest way to do this is
var currentDate=new Date().toLocaleString().slice(0,10);
new Date().toDateString();
Result:
"Wed Feb 03 2016"
The shortest possible.
To get format like "2018-08-03":
let today = new Date().toISOString().slice(0, 10)
console.log(today)
To get format like "8/3/2018":
let today = new Date().toLocaleDateString()
console.log(today)
Also, you can pass locale as argument, for example toLocaleDateString("sr")
, etc.
</div>
Cleaner, simpler version:
new Date().toLocaleString();
Result varies according to the user's locale:
2/27/2017, 9:15:41 AM
This may help you
var date = new Date();
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());
This will print current date in dd/MM/yyyy format
A one-line JS solution:
tl;dr
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
edge, ff latest, & chrome returntodaysDate = "2/7/2017"
"works"* in IE10+
EDIT 2/7/2017
I found out that IE10 and IE Edge do things a bit differently.. go figure. with new Date(Date.now()).toLocaleString()
as input,
IE10 returns:
"Tuesday, February 07, 2017 2:58:25 PM"
I could write a big long function and FTFY. But you really ought to use moment.js for this stuff. My script merely cleans this up and gives you the expanded traditional US notation: > todaysDate = "March 06, 2017"
IE EDGE returns:
"2/7/2017 2:59:27 PM"
Of course it couldn't be that easy. Edge's date string has invisible "•" characters between each visible one. So not only will we now be checking if the first character is a number, but the first 3 characters, since it turns out that any single character in the whole date range will eventually be a dot or a slash at some point. So to keep things simple, just .slice() the first three chars (tiny buffer against future shenanigans) and then check for numbers. It should probably be noted that these invisible dots could potentially persist in your code. I'd maybe dig into that if you've got bigger plans than just printing this string to your view.
∴ updated one-liner:
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
That sucks to read. How about:
var dateString = new Date(Date.now()).toLocaleString();
var todaysDate = dateString.slice(0,3).match(/[0-9]/i) ? dateString.split(' ')[0].split(',')[0] : dateString.split(' ')[1] + " " + dateString.split(' ')[2] + " " + dateString.split(' ')[3];
ORIGINAL ANSWER
I've got a one-liner for you:
new Date(Date.now()).toLocaleString().split(', ')[0];
and [1]
will give you the time of day.
If you are using jQuery. Try this one liner :
$.datepicker.formatDate('dd/mm/yy', new Date());
Here is the convention for formatting the date
Here is the reference for jQuery datepicker
The Shortest Answer is: new Date().toJSON().slice(0,10)
If you are happy with YYYY-MM-DD format, this will do the job as well.
new Date().toISOString().split('T')[0]
2018-03-10
As toISOString()
will only return current UTC time , not local time. We have to make a date by using '.toString()' function to get date in yyyy-MM-dd
format like
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('T')[0]);
To get date and time into in yyyy-MM-ddTHH:mm:ss
format
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);
To get date and time into in yyyy-MM-dd HH:mm:ss
format
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0].replace('T',' '));
</div>