Convert date in ISO YYYY-MM-DDThh:mm:ss.sTZD format - javascript

I want to format date in ISO YYYY-MM-DDThh:mm:ss.sTZD format using javascript.
I can convert current date string in yyyy-MM-dd'T'HH:mm:ss.SSSZ format. For example 2016-01-11T02:40:33.117Z. But I want to get like 2016-01-11T02:40:33.117+1100.
Is it possible in javascript?

Try the following.
var date = new Date(Date.now());
date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
var output = date.toISOString().substring(0, date.toISOString().length - 1) + ((date.getTimezoneOffset() / 60) < 0 ? "-" : "+") + ((Math.abs(date.getTimezoneOffset() / 60) < 10) ? ("0" + Math.abs(date.getTimezoneOffset() / 60)) : test) + "00";
The output variable should be close to what you are looking for. (the + and - may be inversed)
NOTE: There may exist a better solution; I will post it if I find it.

function getCurrentDateFormated() {
var date = new Date();
date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
var timeZoneHours = date.getTimezoneOffset() / 60;
var finalHours = Math.abs(timeZoneHours) < 10 ?
timeZoneHours < 0 ? '-0' + timeZoneHours.toString().substring(1)
: '+0' + timeZoneHours.toString().substring(1)
: timeZoneHours;
var timeZoneMin = ((timeZoneHours - Math.floor(timeZoneHours)) * 60) < 10 ?
'0' + (timeZoneHours - Math.floor(timeZoneHours)) * 60 : (timeZoneHours - Math.floor(timeZoneHours)) * 60;
var timeZone = finalHours + timeZoneMin;
return date.toISOString().substring(0, 20) + date.getMilliseconds() + timeZone;
}

Related

How to add hours to string formatted as HH:MM:SS in 24 hour format

I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59

Get weeks from two dates jQuery

How to get number of weeks from two dates in jQuery 1.0?
I have tried this but no luck:
//start and end date is in format '10-0ct-2015'
var end = $("span[id$=spEstDeliveryDate] input[type=text]").val();
var start = $("span[id$=spPODeliveryDate] input[type=text]").val();
var f = $.datepicker.parseDate("dd-M-yy", end);
var date1 = new Date(f);
date1 = (date1.getDate() + '/' + (date1.getMonth() + 1 ) + '/' + date1.getFullYear());
f = $.datepicker.parseDate("dd-M-yy", start);
var date2 = new Date(f);
date2 = (date2.getDate() + '/' + (date2.getMonth() + 1) + '/' + date2.getFullYear());
var totalWeeks = Math.floor((date1 - date2 + 1) / (1000 * 60 * 60 * 24) / 7);
You convert the dates to strings before trying to do the math on them. Leave them as Date objects:
var f = $.datepicker.parseDate("dd-M-yy", end);
var date1 = new Date(f);
f = $.datepicker.parseDate("dd-M-yy", start);
var date2 = new Date(f);
var totalWeeks = Math.floor((date1 - date2) / (1000 * 60 * 60 * 24) / 7);

Dividing hh:mm:ss by an integer in Javascript

I need to split time (hh:mm:ss) by an integer. For example 13:14:24 / 12.
If I convert it into date and divide:
new Date( date.getMonth()+1 + " " +
date.getDate() + ", " +
date.getFullYear() + " " +
"13:14:24") / 12;
I get a really long number 119579922000, is it date / 12 in milliseconds? I need the result to be in the same hh:mm:ss format.
var h = 13, m = 14, s = 24;
var secsSinceMidnight = (h*3600) + (m*60) + s;
var oneTwelth = secsSinceMidnight / 12;
h = Math.floor(oneTwelth / 3600);
m = Math.floor( (oneTwelth % 3600) / 60);
s = Math.floor( (oneTwelth % 3600) % 60);
console.log(h + ":" + m + ":" + s);
Here is an alternative approach using the Sugar.js library, which is my personal choice extension for date handling in JavaScript:
var midnight = Date.create().beginningOfDay();
var secsSinceMidnight = Date.create().secondsSince(midnight);
console.log( (secsSinceMidnight/12).secondsAfter(midnight) );
To explain the last line: secondsAfter is a function defined on the Number type. It is returning a Date object, which is then sent to console.log().
Just another plain-old-javascript alternative, but done in one line of code.
return (new Date((date - date.getTimezoneOffset() * 60000) % 86400000 / divisor )).toUTCString().split(' ')[4];
It adjusts by timezone (minutes) as the math is in UTC. Next divides the modulo (86400000 milliseconds = 1 day) by a divisor. Returns a formatted time string.
Working Example:
function getTimeSlice( date, divisor ) {
return (new Date((date - date.getTimezoneOffset() * 60000) % 86400000 / divisor )).toUTCString().split(' ')[4];
}
// Test
var test = new Date( );
test.setHours(13, 14, 24, 0);
stdout.innerHTML = getTimeSlice( test, 12);
<div id="stdout"></div>
Not quite sure what you're trying to do, but it might help to have a couple of simple functions, one to convert h:m:s to seconds, and one to convert seconds to h:m:s.
E.g.
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
// Convert seconds to hh:mm:ss
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60 |0);
}
So if you want to divide a time by 12, then:
console.log(secondsToHMS(hmsToSeconds('13:14:24')/12)); // 01:06:12

Countdown count with GMT time from server

I need to work on a countdown counter for a specific future date-time. I managed to use following counter http://www.blacktie.co/demo/counter/ and made some minor changes to it when i was almost done i noticed that this counter use local system date & when i change the system date it is reflected on the counter. How can this script be modified to so that it will take GMT date from server when it starts counter rather than local date.
So that every users irrespective of their location will see the exact date-time of even happening in India.
Fiddle example
http://jsfiddle.net/635hf1je/1/
script
(function ($) {
/**
* Set your date here (YEAR, MONTH (0 for January/11 for December), DAY, HOUR, MINUTE, SECOND)
* according to the GMT+0 Timezone
**/
var launch = new Date(2014, 11, 04, 12, 00);
/**
* The script
**/
var message = $('#message');
var days = $('#days');
var hours = $('#hours');
var minutes = $('#minutes');
var seconds = $('#seconds');
setDate();
function setDate() {
var now = new Date();
if (launch < now) {
days.html('<h1>0</H1><p>Day</p>');
hours.html('<h1>0</h1><p>Hour</p>');
minutes.html('<h1>0</h1><p>Minute</p>');
seconds.html('<h1>0</h1><p>Second</p>');
message.html('coming soon...');
} else {
var s = -now.getTimezoneOffset() * 60 + (launch.getTime() - now.getTime()) / 1000;
var d = Math.floor(s / 86400);
days.html('<h1>' + d + '</h1><p>Day' + (d > 1 ? 's' : ''), '</p>');
s -= d * 86400;
var h = Math.floor(s / 3600);
hours.html('<h1>' + h + '</h1><p>Hour' + (h > 1 ? 's' : ''), '</p>');
s -= h * 3600;
var m = Math.floor(s / 60);
minutes.html('<h1>' + m + '</h1><p>Minute' + (m > 1 ? 's' : ''), '</p>');
s = Math.floor(s - m * 60);
seconds.html('<h1>' + s + '</h1><p>Second' + (s > 1 ? 's' : ''), '</p>');
setTimeout(setDate, 1000);
message.html('coming soon...');
}
}
})(jQuery);
Are you looking for this : http://jsfiddle.net/lotusgodkk/635hf1je/2/ ?
Just convert the Javascript Date object into UTC.
var t = new Date();
var now = new Date(t.getUTCFullYear(), t.getUTCMonth(), t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds());
in setDate() function.
You can use php for getting the server time:
var now = <?php echo date("Y-m-d H:i:s");// Format it as you need it ?>

Javascript: How to turn the time (stored as a fraction) into a readable string?

I have the time stored as a fraction (done so it can be displayed on a graph), e.g. 15.5 is 3.30pm and 23.25 is 11.15pm. I need to turn those numbers into strings in the format HH:MM:SS. Is there a simple way of doing this?
var fraction = 23.5;
var date = new Date(2000, 1, 1); // use any date as base reference
date.setUTCSeconds(fraction * 3600); // add number of seconds in fractional hours
Then use a date formatting script such as this, or Date.js if you're not fond or formatting and padding.
date.format("HH:MM:ss"); // 23:30:00
See an example. I'm using the formatting function from here.
Something like this ?
var fraction = 14.5;
var hours = Math.floor(fraction); // extract the hours (in 24 hour format)
var mins = 60 * (fraction - hours); // calculate the minutes
t = new Date(); // create a date/time object
t.setHours(hours); // set the hours
t.setMinutes(mins); // set the mins
console.log(t.toTimeString()); //show it
or completely manual
var fraction = 14.5;
var hours = Math.floor(fraction);
var mins = 60 * (fraction - hours);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + mins).substr(-2) + ':00 ' + ampm;
console.log(formatted);
Update
And a version with seconds as well..
var fraction = 14.33;
var hours = Math.floor(fraction);
var allseconds = 3600 * (fraction - hours);
var minutes = Math.floor(allseconds / 60);
var seconds = Math.floor(allseconds % 60);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2) + ' ' + ampm;
console.log(formatted);
Manual function:
var time = function(num) {
if(num < 0 || num >= 24) {throw "Invalid number");}
var x = num > 13 ? num - 12 : num;
var h = Math.floor(x);
var min = x - h;
var ampm = num >= 12 && num < 24 ? "pm" : "am";
return (h + ":" + Math.floor(min * 60) + ampm);
};
Tests:
time(13.40); // 1:24pm
time(11.25); // 11:15pm
time(12.50); // 12:30pm
time(23.50); // 11:30pm
time(0.50); // 0:30am
time(24.00); // error!!

Categories

Resources