Add seconds to formatted time from cell - javascript

I get this formatted time HH:MM:SS:MS.
$('#myTable').jqGrid('getCell', rowid, "time")
This give me a value from a cell. Lets say it is: 00:00:07:57 I want to add 30 seconds so it says: 00:00:37:57.
How I formate the time:
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
var ms = date.getMilliseconds();
if (hh < 10) { hh = "0" + hh; }
if (mm < 10) { mm = "0" + mm; }
if (ss < 10) { ss = "0" + ss; }
if (ms < 10) { ms = "0" + ms; }
// This formats your string to HH:MM:SS:MS
ms = ((ms).toString().substr(0, 2));
var formattedTime = hh + ":" + mm + ":" + ss + ":" + ms;

I don't know why you're using a Date. Consider creating a function to convert the time to milliseconds and another to convert milliseconds back to the required time format. Then two formatted times can be added, e.g.
// Convert time in format hh:mm:ss:zz
// where zz is milliseconds
function timeToMs(s) {
var b = s.split(/\D/);
return b[0]*3.6e6 + b[1]*6e4 + b[2]*1e3 + b[3]*10;
}
// Convert milliseconds to time in format hh:mm:ss:zz
// where zz is milliseconds
function msToTime(ms) {
function z(n){return (n<10? '0' : '') + n;}
return z(ms/3.6e6|0) + ':' +
z((ms%3.6e6)/6e4|0) + ':' +
z((ms%6e4)/1e3|0) + ':' +
z((ms%1e3)/10|0);
}
// Add time in format hh:mm:ss:zz
// to time in format hh:mm:ss:zz
function addTime(t0, t1) {
return msToTime(timeToMs(t0) + timeToMs(t1));
}
var x = '02:01:01:10'; // time
var y = '00:00:30:00'; // add 30 seconds
document.write(x + ' + ' + y + ' = ' + addTime(x, y));
x = '00:00:07:57';
y = '00:00:30:00'; // add 30 seconds
document.write('<br>' + x + ' + ' + y + ' = ' + addTime(x, y));
x = '08:53:19:57';
y = '06:23:58:09';
document.write('<br>' + x + ' + ' + y + ' = ' + addTime(x, y));

Related

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

Date.ISOString wrongly converts from timestamp? [duplicate]

Timestamp:
1395660658
Code:
//timestamp conversion
exports.getCurrentTimeFromStamp = function(timestamp) {
var d = new Date(timestamp);
timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();
return timeStampCon;
};
This converts the time stamp properly in terms of time format, but the date is always:
17/0/1970
Why - cheers?
You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :
var d = new Date(timestamp*1000);
Reference
function convertTimestamp(timestamp) {
var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0.
dd = ('0' + d.getDate()).slice(-2), // Add leading 0.
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2), // Add leading 0.
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
// ie: 2014-03-24, 3:00 PM
time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
return time;
}
You can get the value by calling like convertTimestamp('1395660658')
Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.
//time in seconds
var timeInSeconds = ~(new Date).getTime();
//invalid time
console.log(new Date(timeInSeconds));
//valid time
console.log(new Date(timeInSeconds*1000));
const timeStamp = 1611214867768;
const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)

Get time in 24 hrs format and hold it in any variable using Javascript AngularJS

I am creating a time slot in Javascript. Please no jQuery. If you put the first time and last time, then it will make a lists of interval and after 12 number, it will change to am to pm. Suppose, if your start time is 11 and end time is 19, then it will make a slot like like this,
11AM-12PM
12PM-1PM
1PM-2PM
2pm-3pm
3pm-4pm
4pm-5pm
5pm-6pm
6pm-7pm
But, problem is I am taking it as simple integer and giving for loop. I want hold the 24 hrs format of it, like for
1PM-2PM
it should take this value in any variable which will send to server
13:00:00 - 14:00:00
Here is my JS code.
getTimeValues: function() {
console.log('here i am');
var timeValues = this.timeValues;
var minTime = 11; //vary this to change the first
var maxTime = 19; //vary this to chage the
var string;
for (var i = minTime; i < maxTime; i++) {
if(i<12) {
lowersuffix = 'AM';
startRange = i;
}
else if(i===12){
lowersuffix = 'PM';
startRange = i;
}
else {
lowersuffix = 'PM';
startRange = i - 12;
}
if((i+1)<12) {
uppersuffix = 'AM';
endRange = (i+1);
}
else if((i+1)===12){
uppersuffix = 'PM';
endRange = (i+1);
}
else {
uppersuffix = 'PM';
endRange = (i+1) - 12;
}
string = startRange + lowersuffix + '-' + endRange + uppersuffix;
console.log(string);
timeValues.push(string);
};
},
Are you looking for this?
for (var i = minTime; i < maxTime; i++) {
string = i + ':00:00 - ' + (i+1) + ':00:00';
console.log(string);
timeValues.push(string);
};
It seems you're after a simple function to convert time in am/pm format to 24hr format. The following should do the job, hopefully the comments are sufficient. If not, ask.
/* #param {string} time - time string in hh:mm:ss am/pm format
** - missing time parts are treated as 0
** #returns {string} time in 24hr format: hh:mm:ss
**/
function to24hrTime(time) {
// Get the digits from the string
var b = time.match(/\d+/g);
// Test whether it's am or pm, default to am
var pm = /pm$/i.test(time);
var h, m, s;
// If no digits were found, return undefined
if (!b) return;
// Otherwise, convert the hours part to 24hr and two digits
h = ('0' + ((pm? 12:0) + (b[0]%12))).slice(-2);
// Convert minutes part to two digits or 00 if missing
m = ('0' + (b[1] || 0)).slice(-2);
// Convert seconds part to two digits or 00 if missing
s = ('0' + (b[2] || 0)).slice(-2);
// Return formatted string
return h + ':' + m + ':' + s;
}
document.write(
to24hrTime('3:15pm') + '<br>' +
to24hrTime('3:15am') + '<br>' +
to24hrTime('11am') + '<br>' +
to24hrTime('11pm') + '<br>' +
to24hrTime('12AM') + '<br>' +
to24hrTime('12PM') + '<br>' +
to24hrTime('11 pm') + '<br>' +
to24hrTime('12 AM') + '<br>' +
to24hrTime('12 PM')
);

looping and print a list of time

var firstAm = '<li>12:00 AM</li>';
$('#time').append(firstAm);
for (i = 1; i < 12; i++) {
var am = '<li>' + i + ':00 AM</li>';
$('#time').append(am);
}
With above code I produced 1 hour interval, but I wish to produce something like
12:15 AM
12:30 AM
12:45 AM
which have 15 min different.
Fiddle : http://jsfiddle.net/ycjkqc0g/1/
You could do something like
var date = new Date();
date.setHours(0, 0, 0, 0);
var end = new Date(date);
end.setHours(end.getHours() + 12);
while (date < end) {
var am = '<li>' + convert24HourTo12Hour(date.getHours()) + ':' + date.getMinutes() + ' AM</li>';
$('#time').append(am);
date.setMinutes(date.getMinutes() + 15);
}
function convert24HourTo12Hour(h) {
return (h + 11) % 12 + 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
You can add one more loop inside the for loop as,
for (i = 1; i < 12; i++) {
for ( min = 0; min < 3; min++ ) {
var am = '<li>' + i + ':' + min * 15 + 'AM</li>';
$('#time').append(am);
}
}
In the inner loop you are basically printing the time in minutes as 0, 15, 30 and 45.
If you want to print it as '00' for hour, then you can format the number min*15 to a two digit value and use it.
var d = new Date();
d.setHours(0,0,0);
var html = '';
for (i=0;i<12*4*2;i++) {
var h = ('0'+d.getHours()).slice(-2);
var m = ('0'+d.getMinutes()).slice(-2);
var s = ('0'+d.getSeconds()).slice(-2);
var ampm = '';
if (h >= 12) {
ampm = 'pm';
} else {
ampm = 'am';
}
html += '<li>' + h + ':' + m + ':' + s + ' ' + ampm + '</li>';
d.setMinutes(d.getMinutes() + 15);
}
$(html).wrap('<ul></ul>');
$('#time').append(html);

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