Javascript Slicing date/time with leading zero - javascript

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);

Related

js dates pass in a function

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);

Converting DateTimeOffset string value to Date object in javascript

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

Formatting Date in javascript [duplicate]

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.

SetTimeout is returing wrong value

function updateTime() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
var t = hours + " " + minutes + " " + seconds;
var x = d + " " + t;
return x;
}
console.log(updateTime());
var timerId = setTimeout(updateTime(), 1000);
alert(timerId);
Am trying to do a javascript timer. Here UpdateTime function is working properly. Its returing the exact result. But time is constantly being displayed. It should change according to the system time. Hence am using the setTimeout function. But its not returing the proper value. Can anyone help me out here please?
You should remove the alert and () from setTimeout's callback function,
Your code should be
function updateTime() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
var t = hours + " " + minutes + " " + seconds;
var x = d + " " + t;
return x;
}
setTimeout(updateTime, 1000);
timer in javascript with current date
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
what would you do ?
I just edit Your code hope it will help you
function updateTime() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
var t = hours + " " + minutes + " " + seconds;
var x = d + " " + t;
alert(x);/*display time */
}
setTimeout(updateTime, 1000);/* just remove () braces from your code */

Passing Date argument to function

How to pass argument of Date to another function? My code:
var myDate = new Date(data.GetOPCResult.DateTime.match(/\d+/)[0] * 1);
var datlabel = document.getElementById("ct");
datlabel.innerHTML = GetTime(myDate);
And GetTime function code:
function GetTime(DateTime) {
var month = (DateTime.getMonth() < 10) ? "0" + (DateTime.getMonth() + 1) : (DateTime.getMonth() + 1);
var day = (DateTime.getDate() < 10) ? "0" + DateTime.getMonth() : DateTime.getMonth();
var hour = (DateTime.getHours() < 10) ? "0" + DateTime.getHours() : DateTime.getHours();
var minute = (DateTime.getMinutes() < 10) ? "0" + DateTime.getMinutes() : DateTime.getMinutes();
var second = (DateTime.getSeconds() < 10) ? "0" + DateTime.getSeconds() : DateTime.getSeconds();
return DateTime.getDate() + "." + month + "." + DateTime.getFullYear() + " " + hour + ":" + minute + ":" + second;
}
This works for me
function GetTime(d) {
var month = (d.getMonth() < 10) ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1);
var day = (d.getDate() < 10) ? "0" + d.getMonth() : d.getMonth();
var hour = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minute = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var second = (d.getSeconds() < 10) ? "0" + d.getSeconds() : d.getSeconds();
return d.getDate() + "." + month + "." + d.getFullYear() + " " + hour + ":" + minute + ":" + second;
}
alert(GetTime(new Date()));
Are you sure you are passing a valid Date object? Try passing new Date() instead of myDate to your GetTime. If that works, your myDate variable is not a valid Date object.
Your code is fine. A little re-factoring will help though.
function GetTime(date) {
var day = zeroPad(date.getDate(), 2);
var month = zeroPad(date.getMonth() + 1, 2);
var year = zeroPad(date.getFullYear(), 4);
var hour = zeroPad(date.getHours(), 2);
var minute = zeroPad(date.getMinutes(), 2);
var second = zeroPad(date.getSeconds(), 2);
return day + "." + month + "." +
year + " " + hour + ":" +
minute + ":" + second;
}
function zeroPad(num, count) {
var z = num + '';
while (z.length < count) {
z = "0" + z;
}
return z;
}
Also please check what is data.GetOPCResult.DateTime. I would say this will do.
var myDate = new Date( (data.GetOPCResult.DateTime || "")
.replace(/-/g,"/")
.replace(/[TZ]/g," ") );

Categories