var now = new Date('18/10/2016 10:31:22PM');
var time = now.toLocaleTimeString();
alert(time);
this function give an output invalid date. I want to convert this "18/10/2016 22:31:22" format. give me an appropriate example as a solution.
this function should work for your date format
function convertDate(date_string){
var d = date_string.trim();
d = d.split(" ");
v = d[1].split(":")[0];
v = d[1].indexOf("PM")>-1 ? +v+12 : v;
d[1] = d[1].replace(d[1].split(":")[0],v);
d = d.join(" ").replace("PM","").replace("AM","");
return d;
}
console.log(convertDate("18/10/2016 10:31:22PM"));
console.log(convertDate("01/10/2016 09:31:22PM"));
console.log(convertDate("06/10/2016 2:31:22AM"));
console.log(convertDate("07/10/2016 7:31:22AM"));
Without using a library, you will need to extract all the date tokens and send them into a new date object in the correct order. From there, you can create your own date formatting function.
var DATE_FORMAT = /(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}):(\d{2})([AP]M)/;
var dateStr = '18/10/2016 10:31:22PM';
var now = parseDateString(dateStr, DATE_FORMAT, function(tokens) {
return [
parseInt(tokens[3], 10), // year
parseInt(tokens[2], 10) - 1, // month
parseInt(tokens[1], 10), // date
to24(parseInt(tokens[4], 10), tokens[7]), // hours, meridiem
parseInt(tokens[5], 10), // minutes
parseInt(tokens[6], 10), // seconds
0 // milliseconds
];
});
document.body.innerHTML = formateDate(now);
function parseDateString(dateStr, dateFormat, func) {
var tokens = dateStr.match(dateFormat);
var args = Array.prototype.concat.apply([null], func(tokens));
return new (Function.prototype.bind.apply(Date, args));
}
function formateDate(date, dateSeparator) {
return [
pad2(date.getDate()),
pad2(date.getMonth() + 1),
date.getFullYear()
].join(dateSeparator || '/') + ' ' + [
pad2(date.getHours()),
pad2(date.getMinutes()),
pad2(date.getSeconds())
].join(':');
}
function pad2(str) { return ('00' + str).substr(-2); }
function to24(hours, meridiem) {
switch (meridiem) {
case 'PM': if (hours < 12) return hours + 12;
case 'AM': if (hours === 12) return hours - 12;
default: return hours;
}
}
Of course, this can be done in moment with one line.
var dateStr = '18/10/2016 10:31:22PM';
var time = moment(dateStr, 'DD/MM/YYYY hh:mm:ssA').format('DD/MM/YYYY HH:mm:ss');
document.body.innerHTML = time;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
Normally if I wanted to get the date I could just do something like
var d = new Date();
console.log(d);
The problem with doing that, is when I run that code, it returns:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:
8/24/2015
Or, maybe MM-DD-YYYY H:M
8/24/2016 4:20
Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.
var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>
Please note that the timezone of the formatted string is UTC rather than local time.
The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Yet another way:
var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
By using Moment.js library, you can do:
var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
var today = new Date();
function formatDate(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
//return dd + '/' + mm + '/' + yyyy;
return yyyy + '/' + mm + '/' +dd ;
}
console.log(formatDate(today));
function formatdate(userDate){
var omar= new Date(userDate);
y = omar.getFullYear().toString();
m = omar.getMonth().toString();
d = omar.getDate().toString();
omar=y+m+d;
return omar;
}
console.log(formatDate("12/31/2014"));
What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:
var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM
There is really no need to reinvent the wheel.
If you are trying to get the 'local-ISO' date string. Try the code below.
function (date) {
return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}
+date Get milliseconds from a date.
Ref: Date.prototype.getTimezoneOffset
Have fun with it :)
Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.
function returnYYYYMMDD(numFromToday = 0){
let d = new Date();
d.setDate(d.getDate() + numFromToday);
const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
return `${d.getFullYear()}-${month}-${day}`;
}
console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow
Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.
If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.
date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8
Disclaimer: I developed Date-Mirror.
This will convert a unix timestamp to local date (+ time)
function UnixTimeToLocalDate = function( unix_epoch_time )
{
var date,
str;
date = new Date( unix_epoch_time * 1000 );
str = date.getFullYear() + '-' +
(date.getMonth() + 1 + '').padStart( 2, '0' ) + '-' +
(date.getDate() + '').padStart( 2, '0' );
// If you need hh:mm:ss too then
str += ' ' +
(date.getHours() + '').padStart( 2, '0' ) + ':' +
(date.getMinutes() + '').padStart( 2, '0' ) + ':' +
(date.getSeconds() + '').padStart( 2, '0' );
return str;
}
If you want a text format that's good for sorting use:
function formatDateYYYYMMDDHHMMSS(date){
// YYYY-MM-DD HH:MM:SS
const datePart = date.toISOString().split("T")[0]
const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
return datePart + timePart
}
As prototype:
Date.prototype.toSortString = function(){
const date = new Date(this.valueOf());
return date.toISOString().split("T")[0] +
date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01'
new Date().toLocaleDateString("fr-CA",
{year:"numeric", month: "2-digit", day:"2-digit"}
)
const padTo2Digits = num => {
return num.toString().padStart(2, '0')
}
const formatDate = date => {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate())
].join('-')
}
let value = formatDate(new Date())
document.getElementById('dayFormatUS').innerHTML = value
const transformDate = date => {
const convert = date.split('-').reverse()
return convert.join('/')
}
document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
Format US -
<span id='dayFormatUS'></span>
</div>
<div>
Format BR -
<span id='dayFormatBR'></span>
</div>
I want to convert UTC time value (e.g.1367214805) to date (in dd-mm-yyyy) format using javascript.
For e.g. in PHP if we use...
<?php Date("d-m-Y",'1367214805'); ?>
... we directly get the date in dd-mm-yyyy format.
Is there any such function in javascript?
- I tried Date() in various ways in javascript but every time it is printing the present date and time!!
Thanks
JavaScript uses millisecond epoch, so you need to multiply your number by 1000.
var t = 1367214805;
var d = new Date(t * 1000);
There are then .getUTCxxx methods to get the fields you want, and then you can just zero pad and concatenate to get the required string.
function epochToDate(t) {
function pad2(n) {
return n > 9 ? n : '0' + n;
}
var d = new Date(t * 1000);
var year = d.getUTCFullYear();
var month = d.getUTCMonth() + 1; // months start at zero
var day = d.getUTCDate();
return pad2(day) + '-' + pad2(month) + '-' + year;
}
Take a look at Moments.js, you should be able to get whatever format you want and easily.
console.log(new Date());
console.log(moment().format("D-M-YY"));
console.log(moment(1367214805 * 1000).format("DD-MM-YY"));
jsfiddle
You could use toISOString method and just ignore everything after the T e.g.
var isoDateStr = myDate.toISOString();
isoDateStr = isoDateStr.substring(0, isoDateStr.indexOf('T'));
This would give you standard UTC date format yyyy-mm-dd. If you need to specifically format the date as dd-mm-yyyy then you can take that result and switch the values i.e.
isoDateStr = isoDateStr.split('-').reverse().join('-');
You can try this:
myDate.toISOString().split('T')[0].split('-').reverse().join('-')
Why not use getUTCxxx() methods?
function formatUTC(time_UTC_in_milliseconds_since_epoch) {
/*
* author: WesternGun
*/
var time = new Date(time_UTC_in_milliseconds_since_epoch);
var formatted = time.getUTCFullYear() + "-"
+ (time.getUTCMonth() + 1).toString() + "-"
+ time.getUTCDate() + " "
+ time.getUTCHours() + ":"
+ time.getUTCMinutes() + ":"
+ time.getUTCSeconds();
return formatted;
}
Remember to add 1 to the month because the range of return value of getUTCMonth() is 0~11.
With your input, we have:
formatUTC(1367214805 * 1000); // return "2013-4-29 5:53:25"
To format the numbers into \d\d form, just create another function:
function normalizeNumber(input, toAdd) {
if (parseInt(input) < 10) {
return toAdd + input;
} else {
return input;
}
}
And use it like normalizeNumber((time.getUTCMonth() + 1).toString(), "0"), etc.
When we call getMonth() and getDate() on date object, we will get the single digit number.
For example :
For january, it displays 1, but I need to display it as 01. How to do that?
("0" + this.getDate()).slice(-2)
for the date, and similar:
("0" + (this.getMonth() + 1)).slice(-2)
for the month.
If you want a format like "YYYY-MM-DDTHH:mm:ss", then this might be quicker:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Or the commonly used MySQL datetime format "YYYY-MM-DD HH:mm:ss":
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
Why not use padStart ?
padStart(targetLength, padString) where
targetLength is 2
padString is 0
// Source: https://stackoverflow.com/a/50769505/2965993
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
This will always return 2 digit numbers even if the month or day is less than 10.
Notes:
This will only work with Internet Explorer if the js code is transpiled using babel.
getFullYear() returns the 4 digit year and doesn't require padStart.
getMonth() returns the month from 0 to 11.
1 is added to the month before padding to keep it 1 to 12.
getDate() returns the day from 1 to 31.
The 7th day will return 07 and so we do not need to add 1 before padding the string.
Example for month:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
You can also extend Date object with such function:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
The best way to do this is to create your own simple formatter (as below):
getDate() returns the day of the month (from 1-31)
getMonth() returns the month (from 0-11) < zero-based, 0=January, 11=December
getFullYear() returns the year (four digits) < don't use 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);
}
I would do this:
var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
}).format(date);
console.log(str); // prints "01/09/2000"
The following is used to convert db2 date format
i.e YYYY-MM-DD using ternary operator
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);
Just another example, almost one liner.
var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
function monthFormated(date) {
//If date is not passed, get current date
if(!date)
date = new Date();
month = date.getMonth();
// if month 2 digits (9+1 = 10) don't add 0 in front
return month < 9 ? "0" + (month+1) : month+1;
}
If it might spare some time I was looking to get:
YYYYMMDD
for today, and got along with:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
This was my solution:
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;
Using Moment.js it can be done like that:
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
Not an answer but here is how I get the date format I require in a variable
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);
Hope this helps!
Ternary Operator Solution
A simple ternary operator can add a "0" before the number if the month or day is less than 10 (assuming you need this information for use in a string).
let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
The more modern approach perhaps, using "padStart"
const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();
then you can build as a template string if you wish:
`${day}/${month}/${year}`
Tip from 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);
http://jsfiddle.net/v4qcf5x6/
new Date().getMonth() method returns the month as a number (0-11)
You can get easily correct month number with this function.
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
I would suggest you use a different library called Moment https://momentjs.com/
This way you are able to format the date directly without having to do extra work
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
Make sure you import moment as well to be able to use it.
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
Hope this helps :D
How it easy?
new Date().toLocaleString("en-US", { day: "2-digit" })
Another options are available such:
weekday
year
month
More info here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options
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];
}
And another version here https://jsfiddle.net/ivos/zcLxo8oy/1/, hope to be useful.
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")
The answers here were helpful, however I need more than that: not only month, date, month, hours & seconds, for a default name.
Interestingly, though prepend of "0" was needed for all above, " + 1" was needed only for month, not others.
As example:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
My solution:
function addLeadingChars(string, nrOfChars, leadingChar) {
string = string + '';
return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}
Usage:
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]))
if u want getDate() function to return the date as 01 instead of 1, here is the code for it....
Lets assume Today's date is 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
I wanted to do something like this and this is what i did
p.s. i know there are right answer(s) on top, but just wanted to add something of my own here
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;
}
If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.
(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;
},