do some math actions with strings in Javascript - javascript

I have two-hour data they are as strings let first = "09:15" let second = "10:15" how can I do some math actions with these strings? for example I want to do console.log(first - second)

Convert them from String to Date using Date.parseExact() from date.js library
var dateString = "10:12";
var date = new Date.parseExact(dateString, "HH:mm");
and then you can use : second.diff(first)

var dateString = "10:12";
var dateString2 = "10:20";
var startTime=moment(dateString, "HH:mm:ss a");
var endTime=moment(dateString2, "HH:mm:ss a");
var duration = moment.duration(endTime.diff(startTime));
var hours = parseInt(duration.asHours());
var minutes = parseInt(duration.asMinutes())-hours*60;
alert (hours + ' hour and '+ minutes+' minutes.')
var result = endTime.diff(startTime, 'hours') + " Hrs and " +
endTime.diff(startTime, 'minutes') + " Mns";
alert(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Also you can use MomentJS JavaScript library .

Related

Convert date to ISOString javascript server side?

i have a date with this format" 20/02/2018 14:40:00 CET" how can i convert it with the format ISOString, i tried this code but i haven't any result !!
function myFunction() {
var d = '20/02/2018 14:40:00 CET';
var n = d.toISOString();
document.getElementById("demo").innerHTML = n;
}
You need to create a new date instance before try use toISOString method, however correct date format is mm/dd/yyyy so try this :
var d = new Date("02/20/2018 14:40:00");
var n = d.toISOString();
console.log(n);
You need to split and re-assemble since European date format (20/02) is not parse-able
var d = '20/02/2018 14:40:00 CET',
parts = d.split(" "),
time = parts[1].split(":"),
dParts = parts[0].split("/");
+time[0]--; // CET is +1 - for more https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
var n = dParts[2] + "-" +
dParts[1] + "-" +
dParts[0] + "T" +
time[0] + ":" +
time[1] + ":" +
time[2] + ".000Z";
console.log(n);

round up hour difference in time to 2 decimal places with javascript

i'm trying to calculate the hours difference between to times using javascript. But i keep get the results NaN in the console. I get the current time using javascript and the late time from the localstorage
var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
the time from the localstorage reads 15/7/2017 9:30:46
You need to change your date format little bit This may Help you and also parse those dates because those are stirng formate.
Working Fiddle
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))
localStorage will store stringified version of any object, you need to parse it. If you converted it to milliseconds then also you need to parse it to number, it can save only string
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
Then convert diff to hour/minutes/seconds with your logic
Im not shure what youre trying to do here:
date2 - date1
These are booth strings, you cannot substract them. However you might convert them to milliseconds since 1970 which you could then do Math on:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
You may overthink the stored format. Its quite complicated to parse it properly.
http://jsbin.com/fofowayata/edit?console

Javascript : time addition

I have a begin date like this :
var beginDate = "29/04/2015";
var beginHour = "13:32";
I have some duration variables :
var hourDuration = "2";
var minuteDuration = "10";
I have to calculate the end date :
I my example, i attempt to get :
var endDate = "29/04/2015";
var endHour = "15:42";
But if the user set a long hour time for the duration, the endDate must take into account that the end will be another day.
Is there a way in JavaScript to calculate this times ?
without any libraries this would look like this:
var beginDate = "29/04/2015";
var beginHour = "13:32";
var hourDuration = "2";
var minuteDuration = "10";
var date = beginDate.split('/'), time = beginHour.split(':');
date = new Date(date[2], date[1] - 1, date[0], time[0], time[1]);
var newDate = new Date(+date + (hourDuration * 60 + +minuteDuration) * 60000);
var endDate = newDate.getDate() + '/' + (newDate.getMonth() + 1) + '/' + newDate.getFullYear();
var endHour = newDate.getHours() + ':' + newDate.getMinutes();
alert( endDate + ' ' + endHour);
But I would recommend to use momentjs
To have it really accurate you can use the "Date" object in Javascript. Be careful it is aware of the local timezone. The script underneath shows 17:42 instead of 15:42 if you are in GMT+2 (like me :)).
var beginDate = "29/04/2015";
var beginHour = "13:32";
var dateo = new Date(beginDate.split("/").reverse().join("-") + "T" + beginHour + ":00");
var hourDuration = "2";
var minuteDuration = "10";
var enddate = new Date(dateo.getTime() + (hourDuration * 3600000) + (minuteDuration * 60000 ));
alert(enddate);
You can use the built-in Date type from JavaScript:
var date= new Date(2015, 04, 29, 13, 32, 0);
date.setHours(beginDate.getHours()+2);
date.setMinutes(beginDate.getMinutes()+10);
alert( date.getDate() + '/' + date.getMonth() + 1 + '/' + date.getFullYear() +
" " + date.getHours() + ":" + date.getMinutes() );
Javascript has a built in Date object, that can parse RFC2822 compatible date-strings.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
However, your string does not conform to the RFC2822-specification(without prior alterations).
I would therefore recommend you to use momentjs. It's a very convenient library for date/time operations. For instance, to add two hours from your given date, you could type.
var timeString = '29/04/2015 13:32';
var time = moment(timeString, 'mm/dd/yyyy hh:ss').add(2, 'hour');
console.log(time.format('mm/dd/yyyy hh:ss') );
http://momentjs.com/docs/

How to convert Date format in Javascript

I want to change date format sequence from yy-mm-dd to dd-mm-yy
How can I do it in Javascript ?
I have tried
var now = new Date();
now.format("mm-dd-yy");
But its not working for me
Here is a clear and simple approach
var now = new Date();
var dd = now.getDate(); //returns date
var mm = now.getMonth()+ 1; //returns month and you need to add1 because it is array
var yy = now.getFullYear(); //returns full year
var st = dd + '-' + mm + "-" + yy; //format as string
var dateFormatted = (now.getMonth()+1)+"-"+now.getDate()+"-"+now.getFullYear();
You can use the below mentioned function to format Date
utilities.FormatDate(new Date(),"GMT", "dd/MM/yyyy")
function dateformat(date)
{
var yourdate = new Date(date);
yourdate = yourdate.getDate() + '-' + yourdate.getMonth() +1 + "-" +yourdate.getFullYear();
}
use - or / as you like

Javascript/jQuery - DateTime to Date and Time separate strings

Is there any simple way to convert the following:
2011-08-31T20:01:32.000Z
In to UK date format: 31-08-2011
and time to: 20:01
You can use momentjs (http://momentjs.com/):
var date = moment(dateObject).format("YYYY-MM-DD");
var time = moment(dateObject).format("HH:mm:ss");
You can use jquery-dateFormat plugin. The following should do the trick:
$.format.date('2011-08-31T20:01:32.000Z', "dd-MM-yyyy"));
$.format.date('2011-08-31T20:01:32.000Z', "hh:mm"));
Date:
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var date = currentTime.getDate();
var year = currentTime.getFullYear();
$('#date1').html(date + '-' + month + '-' + year);
Time:
<script type="text/javascript">
var tick;
function stop() {
clearTimeout(tick);
}
function clock() {
var ut=new Date();
var h,m,s;
var time="";
h=ut.getHours();
m=ut.getMinutes();
s=ut.getSeconds();
if(s<=9) s="0"+s;
if(m<=9) m="0"+m;
if(h<=9) h="0"+h;
time+=h+":"+m+":"+s;
document.getElementById('clock').innerHTML=time;
tick=setTimeout("clock()",1000);
}
</script>
<body onload="clock();" onunload="stop();">
<p><span id="clock"></span></p>
</body>
var a = '2011-08-31T20:01:32.000Z';
var b = new Date(a);
See http://www.w3schools.com/jsref/jsref_obj_date.asp for methods you can use on b now.
var rg=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\..*/g;
var dateStr="2011-08-31T20:01:32.000Z".replace(rg,"$3-$2-$1"); // result is 31-08-2011
var timeStr="2011-08-31T20:01:32.000Z".replace(rg,"$4:$5"); // result is 20:01
var date = new Date("2011-08-31T20:01:32.000Z").toLocaleDateString();
// date = 2011/08/31
date = date.split("/");
// date = ["31", "08, "2011"]
date = date[2] + "-" + (date[0].length == 1 ? "0" + date[0] : date[0]) + "-" + (date[1].length == 1 ? "0" + date[1] : date[1]);
// data = 2011-31-08
$("#your-txtbox").val(date);
Use the date object:
d = new Date('2011-08-31T20:01:32.000Z');
date = d.format("dd-mm-yyyy");
time = d.format("HH:MM");

Categories