I use Date object to create time in my Javascript code and it should be formated like so : 08:04:21. This is how I tried to do it:
$('#time').click(function(){
var currentTime = new Date();
var Time=currentTime.getHours() + ":"
+ currentTime.getMinutes() + ":"
+ currentTime.setSeconds(currentTime.getSeconds() + 60);
console.log(Time);
$(this).val(Time);
});
But when Time is logged in console string looks like this 8:1:1467844916075. Same happens when i try this:
var Time=currentTime.getHours() + ":"
+ currentTime.setMinutes(currentTime.getMinutes() + 1) + ":"
+ currentTime.getSeconds();
It bring out similar result : 8:1467844916075:3. I even tried this answer: javascript add one minute to time object
$('#time').click(function(){
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
$(this).val(Time);
});
But Time in this case looks like this: 1467785566719. Any idea how to get human readable current time(not date) plus one minute?
You can check this:
Date.getTime() returns you the number of milliseconds since 1970/01/01.
So just grab it and add 1 minute to it to form new milliseconds count for new date.
var d = new Date();
var millisecondssince1970 = d.getTime();
var newMillisec = millisecondssince1970 + (1000 * 60);
var newDate = new Date(newMillisec);
console.log(newDate.getHours() + ":"
+ newDate.getMinutes() + ":"
+ newDate.getSeconds());
Please try this,
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
var date = new Date(Time);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
Here is working example https://jsfiddle.net/oa7j3krs/2/
$('#time').click(function(){
var d = new Date($.now()+60*1000); // current time + 60s
$(this).val(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
});
Anyway, I found a way to do this. Maybe it's not the best but it will do the job.
$('#time').click(function(){
var currentTime = new Date();
var addOneMinute = currentTime.getMinutes();
addOneMinute=parseInt(addOneMinute) + 1;
var Time=currentTime.getHours() + ":"
+ addOneMinute + ":"
+ currentTime.getSeconds();
console.log(Time);
$(this).val(Time);
});
Related
This question already has answers here:
how to convert the minutes into hours and minutes with subtracted time(subtracted time values)
(4 answers)
Closed 4 years ago.
What I have:
Three time inputs consisting of a start time, end time and the difference between the two.
<input type="time" name="starttime" id="starttime">
<input type="time" name="endtime" id="endtime">
<input type="time" name="duration" id="duration" disabled>
What I need:
When the start or end time changes, the difference shows in the third input.
e.g. 23:15 - 20:00 = 03:15.
What I've tried:
So far, I can only produce the correct hours but not the minutes.
<script>
jQuery(document).ready(function($) {
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
// Attempt 1: Only gets hours.
//var difference_as_hours = difference / 60 / 60 / 1000;
//alert("Hour Difference: " + difference_as_hours);
// Attempt 2: Nothing happens.
//var difference_as_hours_and_minutes = difference.getHours() + ":" + difference.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_and_minutes);
// Attempt 3: Nothing happens.
//var difference_as_date = new Date("01/01/2007 " + difference);
//var difference_as_hours_and_minutes = difference_as_date.getHours() + ":" + difference_as_date.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_minutes);
// Attempt 4: Nothing happens.
var formatted_time = time_format(difference);
alert(formatted_time);
}
$("#starttime, #endtime").change(calculateTime);
calculateTime();
});
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? "0" + n : n;
}
</script>
How can I produce the hours and minutes?
Check below working Demo using momentjs:
let valuestart = moment.duration("20:00", "HH:mm");
let valuestop = moment.duration("23:15", "HH:mm");
let difference = valuestop.subtract(valuestart);
console.log(difference.hours() + ":" + difference.minutes())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
You try
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
var time = msToTime(difference);
console.log(time);
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
$("#starttime, #endtime").change(calculateTime);
I have an application which displays the amount of work somebody has done on a specific topic.
There I am receiving a timespan which I wan't to format in hours. When trying to format the timespan using Date it returns NaN, because a day can't have more than 24 hours.
received timespan: {6.20:37:30.9980000}
desired output (hh:mm:ss): 32:50:37
function timeToday() {
var url = "#Url.Action("CalcTimeToday")";
$.get(url, function (time) {
var totalTime = new Date("0001/01/01 " + time);
var h = format(totalTime.getHours(), 2);
var m = format(totalTime.getMinutes(), 2);
var s = format(totalTime.getSeconds(), 2);
totalTime = h + ":" + m + ":" + s;
$('#timeToday').html(totalTime);
})
};
As in the problem stated, it's not possible to format a timespan greater than 24 hours when using Date, as a day does not have more than 24 hours.
I now instead format the timespan to seconds and then calculate the time using Math.floor.
function timeToday() {
var url = "#Url.Action("CalcTimeToday")";
$.get(url, function (seconds) {
var hours = Math.floor(seconds / 3600).toLocaleString('de-CH', { minimumIntegerDigits: 2, useGrouping: false });
seconds %= 3600;
var minutes = ("0" + Math.floor(seconds / 60)).slice(-2);
seconds = ("0" + (seconds % 60)).slice(-2);
var time = hours + ":" + minutes + ":" + seconds;
$('#timeToday').html(time);
})
};
I have been following Convert a Unix timestamp to time in JavaScript thread for answer but looks like single digit time (0-9) is parsed as it is. The accepted answer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
We get like 2:3:9 instead of 02:03:09. How to get rid of this behaviour? Also can anyone please elaborate on how to get am/pm along with time?
var formattedTime = ('0' + hours).substr(-2) + ':'
+ ('0' + minutes).substr(-2) + ':'
+ ('0' + seconds).substr(-2);
I think I will leave the am:pm bit to you. Press ctrl-shift j and play with your code in the console right here
// /*Year m-1 d h m s ms*/
unix_timestamp = Math.floor(new Date(2016,0, 1,5,5,0,0)/1000)
This might be easier to understand. I have kept it closer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var amPm = date.getHours() >= 12?'AM':'PM'
// % is modulo which is the remainder after division || will change 0 to 12
// because 0 is falsey everything else will be left as it is
var hours = ("0" + ((date.getHours() % 12)||12)).substr(-2)
// Minutes part from the timestamp
var minutes = ("0" + date.getMinutes()).substr(-2)
// Seconds part from the timestamp
var seconds = ("0" + date.getSeconds()).substr(-2)
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes+ ':' + seconds + ' '+ amPm
I think you have to get rid of the substr-part, since the value should already be correct.
Note: you need to check if the values are already above 9, because you don't need to append anything when it is above 9.
Example
var d = new Date() //Is in milliseconds
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
console.log(hours + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds))
I want to add that these kinds of problems can be easily resolved with using a good library like moment.js
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + "</b>")
//-->
</script>
Getting local comupter time.
I want to get IST time in javascript.
The following will allow you to convert local time to IST time:
var currentTime = new Date();
var currentOffset = currentTime.getTimezoneOffset();
var ISTOffset = 330; // IST offset UTC +5:30
var ISTTime = new Date(currentTime.getTime() + (ISTOffset + currentOffset)*60000);
// ISTTime now represents the time in IST coordinates
var hoursIST = ISTTime.getHours()
var minutesIST = ISTTime.getMinutes()
document.write("<b>" + hoursIST + ":" + minutesIST + " " + "</b>")
need some help with adding extra time to current time
currentTime= new Date();
var hours2 = currentTime.getHours() + 4;
var minutes2 = currentTime.setMinutes(currentTime.getMinutes() + 30);
however it outputs as: 15:1455880112692PM and does not seem to be adding 4.5 hours? anyone have any ideas on this?
That's because you are not getting the minutes, you are getting the Date object. The setMinutes method doesn't return the minutes, it returns the Date object itself. Converting a Date object to a string to display it gives you the time in milliseconds since epoch.
First convert the time, so that you get a correct time that wraps over, and not something like 27:93 instead of 04:33.
currentTime = new Date();
currentTime.setHours(currentTime.getHours() + 4);
currentTime.setMinutes(currentTime.getMinutes() + 30);
Then you can get the hours and minutes from it:
var hours2 = currentTime.getHours();
var minutes2 = currentTime.getMinutes();
Instead of adding 4 hours and 30 minutes, you can add 270 minutes:
currentTime = new Date();
currentTime.setMinutes(currentTime.getMinutes() + 270);
I have a few ideas as to what's wrong:
currentTime= new Date();
var hours2 = currentTime.getHours() + 4;//doesn't call the setHours method
var minutes2 = currentTime.setMinutes(currentTime.getMinutes() + 30);//works fine for me
So
currentTime= new Date();
var hours2 = currentTime.setHours(currentTime.getHours() + 4);//doesn't call the setHours method
var minutes2 = currentTime.setMinutes(currentTime.getMinutes() + 30);//works fine for me
Does work fine, however, you could just do this in a one-liner:
currentTime.setMinutes(currentTime.getMinutes() + 270);
//or in seconds:
currentTime.setSeconds(currentTime.getSeconds() + 270*60);//16200 === 4.5 hrs
//or miliseconds:
currentTime.setTime(currentTime.getTime() + 270*60000);//16200000 === 4.5 hrs
You never set the hours. Try:
currentTime= new Date();
currentTime.setHours(currentTime.getHours() + 4);
currentTime.setMinutes(currentTime.getMinutes() + 30);
Try this I really dont see what the problem you are having is?
http://jsfiddle.net/H9edz/
currentTime= new Date();
var hours2 = currentTime.getHours() + 4;
var minutes2 = currentTime.setMinutes(currentTime.getMinutes() + 30);
document.write("Ending Time: " + currentTime);
document.write("<br/>");
document.write("Ending Minute: " + currentTime.getMinutes());
document.write("<br/>");
var now = new Date();
now.setMinutes(now.getMinutes() + 30);
document.write("Example Time - From Post:" + now)