This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I want date with this format : '%Y-%m-%dT%H:%M:%S+0000'. I wrote a function but still asking myself if there is not better way to do this.
This is my function :
function formatDate() {
var d = new Date();
var year = d.getMonth() + 1;
var day = d.getDate();
var month = d.getMonth() + 1;
var hour = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var date = d.getFullYear() + "-" + (month < 10 ? '0' + month : month) + "-" +
(day < 10 ? '0' + day : day) +
"T" + (hour < 10 ? '0' + hour : hour) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec) + "+0000";
return date;
}
Any ideal on how to do this with less code ?
It can be done in one line. I made two lines to make it simpler. Combine line 2 and 3.
var d = new Date();
date = d.toISOString().toString();
var formattedDate = date.substring(0, date.lastIndexOf(".")) + "+0000";
console.log(formattedDate);
Use moment.js.
moment().format('YYYY-MM-DDTh:mm:ss+0000')
JSBIN
console.log(moment().format('YYYY-MM-DDTh:mm:ss+0000'))
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
var d = new Date();
var dateString = d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+ d.getUTCDate() + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds()+"+0000";
getUTCMonth returns 0 - 11, so want to add one before you convert to string.
Related
I am facing an issue in javascript dates, i want to added this lines in my GetFormattedDate function.
I try , i can't implement this logic in my function
var currentdate = new Date();
var myTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ; //output 18:43
My code:
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " " ;
}
Expected output
`2020-05-12 01:00:00` //if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00:00 and seconds become 0
`2020-05-12 01:30:00 ` //if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30:00 and seconds become 0
Do it when you set the min and seg variables
Replace the two lines
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
with
var min = date.getMinutes() <= 29 ? '00' : '30';
var seg = '00';
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = date.getMinutes() <= 29 ? '00' : '30';
var seg = '00';
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " ";
}
console.log(GetFormattedDate(new Date));
You're passing a string to your function. Based on the link you provided in a comment, you need to parse a string representation of a date into an actual date object: var d = Date.parse("March 21, 2012"); Read more here: https://www.w3schools.com/jsref/jsref_parse.asp
Once you have a new Date object, set its seconds:
var d = new Date();
d.setSeconds(d.getSeconds() <= 29 ? 0 : 30);
Now you can pass d to your function:
GetFormattedDate(d);
I'm using ASP.NET and I have the following string:
2018-12-04T13:53:42.6785734+07:00
I want to convert the string to Date object and format the output string.
My goal: 04/12/2018 13:53:42
I've tried this way but it logged with the wrong result:
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDay(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
// 2/11/2018 13:53:42
console.log(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDate(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
// 2/11/2018 13:53:42
console.log(day + '/' + (month + 1) + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
I changed your code like this, try:
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDate(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
console.log(day + '/' + (month + 1) + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
Would it be acceptable to just manipulate the original string directly without converting to a date object like so? I can really tell what the test cases would be but assuming that the hour number is the same length (04,12) I think the following code should work.
let dt = '2018-12-04T13:53:42.6785734+07:00';
let dArr = dt.substr(0,10).split('-');
let year = dArr[0];
let month = dArr[1];
let day = dArr[2];
let time = dt.substr(11,8);
let str = month+'/'+day+'/'+year+' '+time;
console.log(str)
The following are arrays starting at 0
getDay() Get the weekday as a number (0-6)
getDate() Get the day as a number (1-31)
getMonth() Get the month as a number (0-11)
var dt = new Date("2018-12-04T13:53:42.6785734+07:00");
var day = returnDay(),
month = returnMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds(),
function returnDay(){
var d = (dt.getDate() < 10) ? "0" + (dt.getDate()): dt.getDate();
return d;
}
function returnMonth(){
var m = (dt.getMonth() + 1 < 10) ? "0" + (dt.getMonth()+ 1):dt.getMonth()+ 1;
return m;
}
//04/12/2018 8:53:42
console.log(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
see for more info:
https://www.w3schools.com/js/js_date_methods.asp
Slice it, I have used jQuery in the example because I have used in in another project and this code was just a part of a component, but it should not matter much
var getTimeOnly = new Date().getTime();
var fullDate = new Date($.now()).toString();
var datePartialTime = fullDate.slice(16, 25);
var datePartialDate = fullDate.slice(0, 16);
$('a').html( "on " + datePartialDate + 'at ' + datePartialTime);
Link to pen
https://codepen.io/damPop/pen/zMzBGN
I'm trying to add a leading 0 before a certain part of a date. For example, if it's 9:00am, I want to display 09:00 and not 9:0. I want to be able to add a leading zero, so I can insert it into MySQL coding.
The result I'm getting is
2018-05-029 019:07:016
Here is my Javascript code:
var login_date="";
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth()+1; /*months are from 0 - 11 */
month = '0' + month.toString().slice(-2);
var day = d.getDate();
day = '0' + day.toString().slice(-2);
var hour = d.getHours();
hour = '0' + hour.toString().slice(-2);
var minute = d.getMinutes();
minute = '0' + minute.toString().slice(-2);
var second = d.getSeconds();
second = '0' + second.toString().slice(-2);
login_date = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
console.log(login_date);
You can check for the variable length of characters, if is less than two, then add a 0.
Something like this:
var d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
if (month.toString().length < 2) month = '0' + month;
if (hour.toString().length < 2) hour = '0' + hour;
if (minute.toString().length < 2) minute = '0' + minute;
if (second.toString().length < 2) second = '0' + second;
console.log(year + '-' + month + '-' + day + " " + hour + ":" + minute + ":" + second)
You could just check if the value is smaller then 10 to add an "0" at the beginning.
example
var seconds = seconds < 10 ? '0'+seconds : seconds;
Your final string could be defined like:
var login_date = year + "-"
+ (month < 10 ? "0" + month : month) + "-"
+ (day < 10 ? "0" + day : day) + " "
+ (hour < 10 ? "0" + hour : hour) + ":"
+ (minute < 10 ? "0" + minute : minute) + ":"
+ (second < 10 ? "0" + second : second) ;
You can create a function addZero() that handles the concatenation of a 0 if necessary. Here is the code:
let addZero = (el) => ((el.toString().length == 1) ? '0' : '') + el.toString();
var login_date = "";
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1; /*months are from 0 - 11 */
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
login_date = year + "-" + addZero(month) + "-" + addZero(day) + " " + addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
document.write(login_date);
Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:
var myDate = new Date();
var prettyDate =(myDate.getFullYear() +'-'+ myDate.getMonth()) +'-'+ myDate.getDate();
This would output as:
2011-8-8
I would like it to be:
2011-08-08
The format you seem to want looks like ISO. So take advantage of toISOString():
var d = new Date();
var date = d.toISOString().slice(0,10); // "2014-05-12"
No, there is no nice way to do it. You have to resort to something like:
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
if(month <= 9)
month = '0'+month;
var day= myDate.getDate();
if(day <= 9)
day = '0'+day;
var prettyDate = year +'-'+ month +'-'+ day;
var myDate = new Date();
var m = myDate.getMonth() + 1;
var d = myDate.getDate();
m = m > 9 ? m : "0"+m;
d = d > 9 ? d : "0"+d;
var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;
...and a sample: http://jsfiddle.net/gFkaP/
You can try like this
For day:
("0" + new Date().getDate()).slice(-2)
For month:
("0" + (new Date().getMonth() + 1)).slice(-2)
For year:
new Date().getFullYear();
You will have to manually check if it needs a leading zero and add it if necessary...
var m = myDate.getMonth();
var d = myDate.getDate();
if (m < 10) {
m = '0' + m
}
if (d < 10) {
d = '0' + d
}
var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;
Yes, get String.js by Rumata and then use:
'%04d-%02d-%02d'.sprintf(myDate.getFullYear(),
myDate.getMonth() + 1,
myDate.getDate());
NB: don't forget the + 1 on the month field. The Date object's month field starts from zero, not one!
If you don't want to use an extra library, a trivial inline function will do the job of adding the leading zeroes:
function date2str(d) {
function fix2(n) {
return (n < 10) ? '0' + n : n;
}
return d.getFullYear() + '-' +
fix2(d.getMonth() + 1) + '-' +
fix2(d.getDate());
}
or even add it to the Date prototype:
Date.prototype.ISO8601date = function() {
function fix2(n) {
return (n < 10) ? '0' + n : n;
}
return this.getFullYear() + '-' +
fix2(this.getMonth() + 1) + '-' +
fix2(this.getDate());
}
usage (see http://jsfiddle.net/alnitak/M5S5u/):
var d = new Date();
var s = d.ISO8601date();
For Month,
var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
For Day,
var day = ("0" + (myDate.getDate() + 1)).slice(-2);
Unfortunately there's no built-in date-format in javascript. Either use a existing library (example http://blog.stevenlevithan.com/archives/date-time-format) or build your own method for adding a leading zero.
var addLeadingZeroIfNeeded = function addLeadingZeroIfNeeded(dateNumber) {
if (String(dateNumber).length === 1) {
return '0' + String(dateNumber);
}
return String(dateNumber);
},
myDate = new Date(),
prettyDate;
prettyDate = myDate.getFullYear() + '-' + addLeadingZeroIfNeeded(myDate.getMonth()) + '-' + addLeadingZeroIfNeeded(myDate.getDate());
EDIT
As Alnitak said, keep in mind that month i JavaScript starts on 0 not 1.
The easiest way to do this is to prepend a zero and then use .slice(-2).
With this function you always return the last 2 characters of a string.
var month = 8;
var monthWithLeadingZeros = ('0' + month).slice(-2);
Checkout this example:
http://codepen.io/Shven/pen/vLgQMQ?editors=101
Let say date current date is 10 Jan 2011. When I get date using js code
var now = new Date();
var currentDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();
It reutrns "10-1-2011"
but I want "10-01-2011" (2 places format)
var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))
Here's a nice short way:
('0' + (now.getMonth() + 1)).slice(-2)
So:
var currentDate = now.getDate() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + now.getFullYear();
(now.getMonth() + 1) adjust the month
'0' + prepends a "0" resulting in "01" or "012" for example
.slice(-2) slice off the last 2 characters resulting in "01" or "12"
function leftPad(text, length, padding) {
padding = padding || "0";
text = text + "";
var diff = length - text.length;
if (diff > 0)
for (;diff--;) text = padding + text;
return text;
}
var now = new Date();
var currentDate = leftPad(now.getDate(), 2) + '-' + leftPad(now.getMonth() + 1, 2js) + '-' + now.getFullYear();
the quick and nasty method:
var now = new Date();
var month = now.getMonth() + 1;
var currentDate = now.getDate() + '-' + (month < 10 ? '0' + month : month) + '-' + now.getFullYear();
var now = new Date();
now.format("dd-mm-yyyy");
would give 10-01-2011