Date format with time range in javascript - javascript

I have a javascript date variable as 04/05/2015, 01:30 (dd/mm/yyyy, HH:mm) format. Now how can I change that format to 04/05/2015, 01:00-01:30 format. Ie, I want to change the time with time range where the first time value is always 30 minutes less than second time value. So If the date is 04/05/2015, 13:00 then the formatted date would be 04/05/2015, 12:30-13:30
EDIT: See the fiddle here for the sample.

Please check the below solutions:
http://jsfiddle.net/ub942s6y/14/
You need to change data.addColumn('datetime', 'Date'); to 'string' as we are changing time
It will work fine. :)

Im affraid that there is no out-of-the-box functionality for what you are asking, and you will have to write your own function for that.
Here is a js Date object specification : Date Object
Your new function return type cannot be Date, as this kind of formatting can be only achieved with string type.

You can't have date object in that format. You will have manually create the format. It will be string.
var dateObj = new Date('04/05/2015, 01:30'), // input date
interval = 30, // interval in minutes
remainingInterval = 0;
var hours = dateObj.getHours(),
minutes = dateObj.getMinutes();
if(minutes > interval) {
minutes = minutes - interval;
} else {
remainingInterval = interval - minutes;
minutes = 60;
hours = hours - 1;
minutes = minutes - remainingInterval;
}
resulting date can be
console.log(dateObj.getDate()+'/'+dateObj.getMonth()+'/'+dateObj.getFullYear()+', '+dateObj.getHours()+':'+dateObj.getMinutes()+' - '+hours+':'+minutes);

Related

Moment.js not displaying local Date and Time format

I am trying to display a time stamp for the user if a comment was older than 24 hours. The following code does that but it is still showing my (US) date and time format for my developers in Pakistan. Instead of mm/dd/yy it should display dd/mm/yy. Any reason why it is not working correctly? Here is my code.
//get date of comment
let commentDateUTC = item.createdOn;
//convert it to local time
let commentLocalTime = moment.utc(commentDateUTC).local().toLocaleString();
//determine amount of time elapsed between comment and current time
let nowObj = { 'now': moment(commentLocalTime).fromNow() }
//determine if more than 24 hours has elapsed since the comment was created
let currentTime = moment().local().toLocaleString();
let elapsedTime = moment(currentTime).diff(commentLocalTime, 'hours');
//if yes, concatenate the item.createdOn and the nowObj.now value
if (elapsedTime >= 24) {
nowObj.now = `${moment(commentLocalTime).format('l LT')} (${nowObj.now})`
}
This is the answer. You have to grab the locale from the browser settings and then set it using moment.locale();. I wish the docs were a little more clear on this....
if (elapsedTime >= 24) {
var locale = window.navigator.language;
moment.locale(locale);
nowObj.now = `${moment(commentLocalTime).format('l LT')} (${nowObj.now})`
}

Convert string to time and add some minutes

I have a form and one button to plus some minutes to a time(hh:MM), but the time is a span tag.
At Firefox works well, but when I tested at Chrome doesn't work the Date(). What happened?
//Botão adicionar horário agenda.
$('.button').click(function() {
var $duration_schedule = $('#duration');
var duration = $duration_schedule.val(); // 30
var hour = $('.time_schedule_form').text(); // 10:00
var new_time = self.Plus_minutes(hour, duration);
alert(new_time); // 10:30
});
Plus_minutes: function(hour, duration) {
var time, new_hour, hours = '';
time = new Date("T"+hour); // Erro at Chrome
time.setTime(time.getTime() + duration*60000);
hours = time.getHours().toString();
minutes = time.getMinutes().toString();
if (minutes.length > 1) {
new_hour = hours + ':' + minutes;
} else {
new_hour = hours + ':0' + minutes;
}
return new_hour;
},
I suppose that it is happening because of constructor's input! In case of time you should put numbers in milliseconds. The Data Object have those constructors bellow:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[,milliseconds]]]]]);
you can take at look at Developer.mozilla then you can check a better explanation about formats.
Maybe the Firefox are converting to including something in that part of code. I found out other explanation about Data input formats, you can take a look too at: Convert String to Date
The correct format for UTC would be like 2013-02-27T17:00:00Z (Z is for Zulu Time). Append Z if not present to get correct UTC datetime string.
You could achieve this using setMinutes to update using getMinutes.
newdate.setMinutes(newdate.getMinutes() + 10);

calculate difference in dates, get difference in hours mins and seconds - ideally by js, otherwise moment.js

I've managed in calculating date differences by:
converting unix date received into js date,
Saving current date as js date,
passing both to moment.js together with their format to get diff
converting to milliseconds
difference in ms is converted to a moment and returns hours mins secs
I've run into an issue where specific versions of moment works this out, and others throws exception as nan internally when calc differences. Would love to do it using just plain js, hopefully circumventing this scenario.
Uploaded a fiddle, it doesnt run unless you comment out the moment part since didnt find a moment.js version on cdn.
I'm more after the logic and a bit of pseudocode/syntax rather than a working example. The JS version's issue is that when the calculated difference between both unix dates is then converted into a date *1000 for milliseconds, it becomes a 1970 date. also the getMinutes() in js get the literal minute at that timestamp, not to overall amount of minutes ,same for hours etc..
This is the moment JS example:
var now = new Date(Date.now()),
ms = moment(then, "DD/MM/YYYY HH:mm:ss").diff(moment(now, "DD/MM/YYYY HH:mm:ss")),
d = moment.duration(ms),
formattedMomentDateDifference = Math.floor(d.asHours()) + ":";
formattedMomentDateDifference += Math.floor(d.minutes()) + ":";
formattedMomentDateDifference += Math.floor(d.seconds());
$('#momentdifference').val(formattedMomentDateDifference);
and below is the js dates example:
var then = cleanedReceivedDate, //cleaned received date in unix
difference = Math.floor(then - now)*1000, /* difference in milliseconds */
msDifferenceInDate = new Date(difference),
hoursDiff = msDifferenceInDate.getHours(),
minutesDiff = "0"+msDifferenceInDate.getHours(),
secondsDiff = "0"+msDifferenceInDate.getSeconds(),
formattedTime = hoursDiff + ':' + minutesDiff.substr(-2) + ':' + secondsDiff.substr(-2);
$('#jsdifference').val(formattedMomentDateDifference);
JS fiddle
Matt has linked to a duplicate for moment.js, so this is just a POJS solution.
UNIX time values are seconds since the epoch, ECMAScript time values are milliseconds since the same epoch. All you need to do is convert both to the same unit (either seconds or milliseconds) and turn the difference into hours, minutues and seconds.
The UNIX time value for say 2016-10-02T00:00:00Z is 1475366400, so to get the hours, minutes and seconds from then to now in your host system's time zone, do some simple mathematics on the difference from then to now:
var then = 1475366400, // Unix time value for 2016-10-02T00:00:00Z
now = Date.now(), // Current time value in milliseconds
diff = now - then*1000, // Difference in milliseconds
sign = diff < 0? '-' : '';
diff *= sign == '-'? -1 : 1;
var hrs = diff/3.6e6 | 0,
mins = diff%3.6e6 / 6e4 | 0,
secs = diff%6e4 / 1e3 ;
// Helper to pad single digit numbers
function z(n){return (n<10?'0':'') + n}
console.log(sign + hrs + ':' + z(mins) + ':' + z(secs));
PS
Using Date.now in new Date(Date.now()) is entirely redundant, the result is identical to new Date().

How to get a specific part of moment.js / timezone.js date

I am quite low at javascript. I started to use moment.js library for my project to make javascript code to work by time & date, which always aligned by specific time zone. But I am struggling to understand how access different parts of my variable. My code:
var ItalyZone = "Europe/Rome";
var currentTime= moment().tz(ItalyZone).format();
alert(currentTime.hours()); //this is not working....
How can access only hours/minutes of that variable "currenTime" ?
How to set new hours for that variable "currentTime" ?
Using simple javascript Date() function I could do simply currentTime.getHours() / currentTime.setHours(), but how should I do using moment.js ???
Why use format when you just want the hours, return a date object instead
var ItalyZone = "Europe/Rome";
var currentTime = moment().tz(ItalyZone).toDate(); // return JS date object
var hours = currentTime.getHours()
You can use the get-set function to do this
moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number
Gets or sets the minutes.
You can use date format to get any part of date time:
var ItalyZone = "Europe/Rome";
moment().locale(ItalyZone).format("yyyy"); // year
moment().locale(ItalyZone).format("MM"); // month
moment().locale(ItalyZone).format("DD"); // day
moment().locale(ItalyZone).format("hh"); // hours
moment().locale(ItalyZone).format("mm"); // minutes
moment().locale(ItalyZone).format("ss"); // seconts
console.log(moment().locale(ItalyZone).format("YYYY MM DD hh mm ss"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

Convert any String time to seconds

I'm trying to convert 15:00 (15minutes) to seconds though I get 54,000 when I use this below.
I'm trying to convert 15minutes to seconds.
S = '15:00';
D = "1/1/1 "
s = ( new Date(D+S) - new Date(D) )/1000
alert(s);
Though when I do the math, it's 60 x 15 = 900. How do I get 900, since the time is a random string.
Well if your format will always be "mm:ss" you could dome string parsing and do the math manually, of course this would need to be adjusted depending on the input format.
S = '15:25';
var times = S.split(":");
var minutes = times[0];
var seconds = times[1];
seconds = parseInt(seconds, 10) + (parseInt(minutes, 10) * 60);
alert(seconds);​
Note in the example I explicitly added 25 seconds just as demonstration.
http://jsfiddle.net/Jg4gB/
The time string '15:00' in JavaScript refers to the time of day 1500hr, or 3:00 p.m. American-style. That's 15 hours after midnight. That explains why you got 54,000 seconds.
If you wanted to express 15 minutes using your method of manipulating date strings, try '00:15:00'.

Categories