Convert string to time and add some minutes - javascript

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);

Related

JavaScript Date Validation when using firefox [duplicate]

I am creating a datetime string that looks like this: 2010-07-15 11:54:21
And with the following code I get invalid date in Firefox but works just fine in Chrome
var todayDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
var date1 = new Date(todayDateTime);
In firefox date1 is giving me an invalid date, but in chrome its working just fine what would the main cause be?
You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
or
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
Chrome must just be more flexible.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
From apsillers comment:
the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."
This works in all browsers -
new Date('2001/01/31 12:00:00 AM')
new Date('2001-01-31 12:00:00')
Format: YYYY-MM-DDTHH:mm:ss.sss
Details: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
Option 1 :
Suppose your timestring has a format that looks like this :
'2016-03-10 16:00:00.0'
In that case, you could do a simple regex to convert it to ISO 8601 :
'2016-03-10 16:00:00.0'.replace(/ /g,'T')
This would procude the following output :
'2016-03-10T16:00:00.0'
This is the standard datetime format, and thus supported by all browsers :
document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE
Option 2 :
Suppose your timestring has a format that looks like this :
'02-24-2015 09:22:21 PM'
Here, you can do the following regex :
'02-24-2015 09:22:21 PM'.replace(/-/g,'/');
This, too, produces a format supported by all browsers :
document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE
Option 3 :
Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.
In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date :
document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE
This works in most browsers as well
new Date('2001/01/31 12:00:00')
That is the format of
"yyyy/MM/dd HH:mm:ss"
If you still want to create date using dashes, you can use this format:
var date = new Date('2013-08-31T17:00:00Z')
But bear in mind, that it creates time according to UTC. Meaning, if you live in GMT+3 (3 hours ahead of GMT) timezone, it will add this timezone offset to the time. So the above example will have this value, if GMT+3 (note that it is hour 20:00 and not 17:00):
Sat Aug 31 2013 20:00:00 GMT+0300 (FLE Standard Time)
Be sure to add 'Z' letter at the end, because otherwise Chrome and Firefox will parse the string differently (one will add time offset and the other won't).
I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:
2014-06-02 10:28:00
using this code:
new Date('2014-06-02 10:28:00').toISOString();
returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.
My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.
Using this library the following code works correctly across all browsers I tested:
moment('2014-06-02 10:28:00').format('MMM d YY')
If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.
This should work for you:
var date1 = new Date(year, month, day, hour, minute, seconds);
I had to create date form a string so I have done it like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Simple Solution, This works with All Browsers,
var StringDate = "24-11-2017"
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);
One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date.
"2014/11/24 17:38:20.177Z"
They do not know how to handle .177Z. Chrome will work though.
This is what worked for me on Firefox and Chrome:
// The format is 'year-month-date hr:mins:seconds.milliseconds'
const d = new Date('2020-1-4 12:00:00.999')
// we use the `.` separator between seconds and milliseconds.
Good Luck...
There is a W3C specification defining possible date strings that should be parseable by any browser (including Firefox and Safari):
Year:
YYYY (e.g., 1997)
Year and month:
YYYY-MM (e.g., 1997-07)
Complete date:
YYYY-MM-DD (e.g., 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (e.g., 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (e.g., 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (e.g., 1997-07-16T19:20:30.45+01:00)
where
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
According to YYYY-MM-DDThh:mmTZD, the example 2010-07-15 11:54:21 has to be converted to either 2010-07-15T11:54:21Z or 2010-07-15T11:54:21+02:00 (or with any other timezone).
Here is a short example showing the results of each variant:
const oldDateString = '2010-07-15 11:54:21'
const newDateStringWithoutTZD = '2010-07-15T11:54:21Z'
const newDateStringWithTZD = '2010-07-15T11:54:21+02:00'
document.getElementById('oldDateString').innerHTML = (new Date(oldDateString)).toString()
document.getElementById('newDateStringWithoutTZD').innerHTML = (new Date(newDateStringWithoutTZD)).toString()
document.getElementById('newDateStringWithTZD').innerHTML = (new Date(newDateStringWithTZD)).toString()
div {
padding: 10px;
}
<div>
<strong>Old Date String</strong>
<br>
<span id="oldDateString"></span>
</div>
<div>
<strong>New Date String (without Timezone)</strong>
<br>
<span id="newDateStringWithoutTZD"></span>
</div>
<div>
<strong>New Date String (with Timezone)</strong>
<br>
<span id="newDateStringWithTZD"></span>
</div>
In fact, Chrome is more flexible to deal with different string format. Even if you don't figure out its String format, Chrome still can successfully convert String to Date without error. Like this:
var outputDate = new Date(Date.parse(inputString));
But for Firefox and Safari, things become more complex. In fact, in Firefox's document, it already says: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)
A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).
So, when you want to use Date.parse in Firefox and Safari, you should be careful. For me, I use a trick method to deal with it. (Note: it might be not always correct for all cases)
if (input.indexOf("UTC") != -1) {
var tempInput = inputString.substr(0, 10) + "T" + inputString.substr(11, 8) + "Z";
date = new Date(Date.parse(tempInput));
}
Here it converts 2013-08-08 11:52:18 UTC to 2013-08-08T11:52:18Z first, and then its format is fit words in Firefox's document. At this time, Date.parse will be always right in any browser.
In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate(). Finally compare it with the date.
I have used following date format and it's working in all browser.
var target_date = new Date("Jul 17, 2015 16:55:22").getTime();
var days, hours, minutes, seconds;
var countdown = document.getElementById("countdown");
remaining = setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
countdown.innerHTML = "<b>"+days + " day, " + hours + " hour, "
+ minutes + " minute, " + seconds + " second.</b>";
}, 1000);

JavaScript setHours() and getHours() [duplicate]

I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();

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().

Date format with time range in 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);

How to get current date without time?

I'm trying to get the current date without the time and store it in a variable, within JavaScript. It needs to be without time as I'm converting it to an epoch date, with which I will use to measure the past 24 hours (if date is within 24 hours then it will be displayed). The problem is that with the added time, it doesn't match as within the last 24 hours.
e.g. it returns the date as the following when converted to epoch: 1408704590485
I want it to be like 1408662000000
I'm not to sure how to do this.
Code - How the current days epoch date is currently being stored -
var epochLoggingFrom;
var epochLoggingTo;
$(document).ready(function () {
epochLoggingFrom = dateToEpoch(new Date());
epochLoggingTo = dateToEpoch(new Date());
}
dateToEpoch function -
function dateToEpoch(thedate) {
return thedate.getTime();
}
Try this:
function dateToEpoch(thedate) {
var time = thedate.getTime();
return time - (time % 86400000);
}
or this:
function dateToEpoch2(thedate) {
return thedate.setHours(0,0,0,0);
}
Example : http://jsfiddle.net/chns490n/1/
Reference: (Number) Date.prototype.setHours(hour, min, sec, millisec)
Try this:
var nowDate = new Date();
var date = nowDate.getFullYear()+'/'+(nowDate.getMonth()+1)+'/'+nowDate.getDate();
Note: Adjust format as you want, like reorder day, month, year, remove '/' and get combined date etc.
or use this:
dateToEpoch(new Date().toLocaleDateString())
I tried using javascript. this method returns the current date in "DD/MM/YYYY" format.
getCurrentDate() {
const t = new Date();
const date = ('0' + t.getDate()).slice(-2);
const month = ('0' + (t.getMonth() + 1)).slice(-2);
const year = t.getFullYear();
return `${date}/${month}/${year}`;
}

Categories