Why .getMinutes() output as :0 instead of :00 in JavaScript? - javascript

The .getMinutes() method only outputs one integer ‘0’ instead of two integers ‘00’. Why does it do this and is there a simpler way to fix this?
Example:
var dateDue = new Date("Fri Apr 22 2022 18:00:00");
dateDue.getMinutes(); //Expected output: 18:00, got 18:0 instead?
For now I have been using if statement validation to add 0 whenever the minutes .Length returns as only being one character long instead of two.
//Minutes display validation for dateDue
var minutesDue = dateDue.getMinutes();
if (minutesDue.Length === 1) {
minutesDue = parseInt(dateDue.getMinutes()) + "0";
Coding language: JavaScript (vanilla)
Skill level: Beginner
Editor: Visual Studio Code
OS: Windows 7

You can use the toLocaleTimeString method with some options for padding and even more styling. This one does AM/PM automatically for you.
const time = new Date("Fri Apr 22 2022 18:00:00").toLocaleTimeString('default', { hour: '2-digit', minute: '2-digit' });
console.log(time) // '06:00 PM'

I could answer half the question if it helps to start thinking process. To put :00 for seconds. You need a loop which checks the condition, if seconds less than 9. If that's the case concatenate 0 to secs.

var dateDue = new Date("Fri Apr 22 2022 18:00:00");
if (dateDue.getMinutes() < 10) {
var getMinutes= '0' + dateDue.getMinutes();
}

Related

Conver Timepicker time to utc using Timepicker (ng-bootstrap)

I am using https://valor-software.com/ngx-bootstrap/#/timepicker in my angular project.
I have one task o covert that time to UTC before I request to server.
When I select Time from timepicker value coming is as below.
Now, I have created one function to convert it to UTC using moment.js
static FormatimeSpanBeforeSubmit(date: Date | string ) {
const dateFromTimePicker = date as Date;
// Convert it to format "HH:mm:ss"
let formatedTime = moment.utc(dateFromTimePicker).format('HH:mm:ss');
// Split details in array because I want seconds as always "00"
let list = formatedTime.split(/[\s:]+/);
// Updating last value ""ss" to "00"
formatedTime = formatedTime.replace(new RegExp(list[list.length -1] + '$'), '00');
//Final value
return date ? formatedTime : null;
}
Expected Output : It should convert my time as "9:51:00"
Current Output : "10:54:00"
Please help me and guide me how can I get correct value.
Comment :
(2) As per comments from Hoài Nam I have updated my code like below and in that I am still getting 10:54:00
Please find below two images
i can't comment so i will reply you at here:
i found another solution at here https://stackoverflow.com/a/40381090/9768008
this is what i tried:
var time = 1569326290681; //Tue Sep 24 2019 18:58:10 GMT+0700 (Indochina Time)
var os = new Date().getTimezoneOffset();
var converted = new Date((time + (os * 60 * 1000)));
console.log(converted); // Tue Sep 24 2019 11:58:10 GMT+0700 (Indochina Time)
Issue was date format coming from server was wrong. So, I was getting GMT+ 6.55 instead of GMT+ 8.
Thanks for helping.
Addressed both solution. Mine as well as of #HoàiNam are correct.

How to deduct time in 24 hours using moment

My use case is very simple, How do i deduct the current time in 24 hours. Technically it is like snapchat, 24 hours from now it will dissapear, hence why I need to deduct the time.
11:50 PM - 10 Jan 2017
I want to deduct the current time to the next 24 hours time only
(10:50 PM - 11 Jan 2017) - (11:50 PM 10 Jan 2017) = 1 hour left
How would I do such thing in Moment.js ?
You can add -24 hours. See moment.add
moment(date).add(-24, 'hours');
And to display relative time you can use moment.fromNow
I think this would help you :
//valid formats to subtract
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
//easy examples
var myString = "03:15:00",
myStringParts = myString.split(':'),
hourDelta: +myStringParts[0],
minuteDelta: +myStringParts[1];
date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
Read http://momentjs.com/docs/#/parsing/ for documentation on moment js parse.
This just might work. It did work in JSFiddle http://jsfiddle.net/Bjolja/p2bcm2oa/
var dt = moment("12:15 AM", ["h:mm A"]).format("HH:mm");
Yes you should use moment.js take a look here
Moment from method
In fact you can deduct time passed between to dates like this
var start = moment("10:50 PM - 11 Jan 2017");
var end = moment("11:50 PM 10 Jan 2017");
start.from(end); // "1 hour"

Format the following date into YYYY-mm-dd in JS

How would I go about converting following date:
Thu Feb 18 12:25:00 SGT 2016
into a format like '2016-02-18'?
I know,
That, using a new Date(Date.parse('...')), with calls, will help me get it. But the problem being timezone part (SGT).
I dont want to use any libraries out there.
What would be the effective way to go about this?
Any help is appreciated!
PS:
Ok, I have tried
new Date(Date.parse('Thu Feb 18 12:25:00 SGT 2016'))
but of-course, it is going to me 'invalid date' error.
I guess I should wait for you to post some code, but here's an example. It splits the string into parts, converts the month name to a number, then outputs the bits you want in the order you want. The slice on the month name is just in case you want to use the full month name, but maybe that's unnecessary:
function reformatDate(s){
var b = s.split(/[\s:]/);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b[7] + '/' + months[b[1].toLowerCase().slice(0,3)] + '/' + ('0'+b[2]).slice(-2);
}
document.write(reformatDate('Thu Feb 18 12:25:00 SGT 2016'));
That format date string (y/m/d) isn't consistent with any standard that I know of and likely will not be parsed by most browsers.
Why not just take the individual components of the date object and build a string from them?
full_date = new Date();
formatted_date_string = full_date.getFullYear() + "-" + (full_date.getMonth()+1) + "-" + full_date.getDate();
I'll leave it to you to sort out the leading 0s on the day and month.
var input="Thu Feb 18 12:25:00 SGT 2016";
var ar=input.split(" ");
var months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"};
console.log(ar[ar.length-1]+"-"+months[ar[1]]+"-"+ar[2]);
Try this code no date parsing required. Please check on console for result.
var date = "Thu Feb 18 12:25:00 SGT 2016";
date = date.replace("SGT","GMT+0800") // replaces SGT with GMT+0800 because
singapore time is 8 hrs ahead than GMT timezone
var newdate = new Date(Date.parse(date))
var requiredDate = newdate.toLocaleDateString()

Simple Javascript date conversion

I have this - Tue, 03 Apr 2012 05:00:33 GMT
Need this - 20120323111106
Google has failed me, I think I just don't know exactly what im searching for so I kept it simple here with the question.
EDIT: The dates do not match obviously, just looking to get it in that format.
Good answer (later edited):
I think this is what you are looking for :
function addZero(val){
if (parseInt(val) < 10) return "0" + val;
return val;
}
var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT");
console.log(dt.getFullYear() + addZero(dt.getMonth()) + addZero(dt.getDay()) + addZero(dt.getHours()) + addZero(dt.getMinutes()) + addZero(dt.getSeconds()))
Initial wrong answer :
var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT")
var miliseconds = dt.getTime();
I've tested it and my computer converted it automatically to GMT +3 (my timezone), you can play with that according to your timezone.
Writing a function to parse a string should work for you. By the looks of it, any date string that you currently have will be the same length. If this is the case this should be relatively easy. Just make sure your strings are in this format before you pass them in as arguments.
function parse(string) {
var out = "yyyymmddhhmmss"
out.charAt(0) = string.charAt(13);
out.charAt(1) = string.charAt(14);
out.charAt(2) = string.charAt(15);
out.charAt(3) = string.charAt(16);
//if else statements for each month converting to numbers
if (string.substring(9,12).equals("Apr")) {
out.charAt(4) = '0';
out.charAt(5) = '4';
}
out.charAt(6) = string.charAt(18);
out.charAt(7) = string.charAt(19);
...etc for the remaining values
return out
}
My numbers for character indices may be off, but if you use this idea, it should set you straight. Define a function and pass in the dates in the format you have, and out will come the dates in the format you want.

Problem in adding days / month / year to a given date using javascript?

I trying to add days / months / year to a given date and map it to an input field
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setYear(2011);
document.getElementById("test").innerHTML=d;
d.setDate(d.getDate()+20);
document.getElementById("test").innerHTML+=""+d.getDate()+"/"+d.getMonth()+"/"+d.getYear("YY");
this actually prints out
Fri Jul 15 2011 12:45:48 GMT+0530 (India Standard Time)
4/7/111
actually this is wrong.. it should print out 5/7/2011.. i think by default the system takes as "30" days for a month and adds the +20 days.. but actually Jun has 30 days so that result should be 5/7/2011..
any suggestion about what goes wrong in here.. any alternative for this?
At the first, you have better to use getFullYear to get year as 2011. You did get number from getDate() and add 20. This break Date. You should get long value from getTime(), and add milli-seconds.
<div id="test"></div>
<script>
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setFullYear(2011);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
d.setTime(d.getTime()+1000*60*60*24*20);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
</script>
> var d = new Date();
> d.setDate(15);
> d.setMonth(06);
> d.setYear(2011);
is equivalent to:
var d = new Date(2011,6,15); // 15 Jul 2011
Months are zero based (January = 0, December = 11).
Date.prototype.getYear is specified in ECMA-262 ed5 as Return YearFromTime(LocalTime(t)) − 1900. so:
alert(d.getYear()); // 111
whereas:
alert(d.getFullYear()); // 2011
i think by default the system takes as "30" days for a month and adds the +20 days.. but actually May has 31 days so that result should be 5/7/2011.
You are interpreting it a wrong way, Month in a date starts with 0 - Jan..
So as per the date entered by you it comes Jul 15 2011 on the month number 6.
When you add 20 to date it will be Aug 04 2011 and you are directly getting month number which is 7 - i.e. Aug which misleads your calculation. And for the year, yes it is you should getFullYear
Read this to get your basics correct..

Categories

Resources