How can I parse timespan string to hour, minutes? - javascript

I have a string "P18DT5H2M3S" which means: 18 days, 5 hours, 2 minutes, 3 seconds.
I have to parse this string to hour and minute. Should I use regex or split or substr etc...?
(regarding to this How can I convert come string timespan variable from Wcf to hours and minutes?)

You can use whatever you want.
Following is the example using split method with regex.
var res = "P18DT5H2M3S";
var tokens = res.split(/[A-Z]+/);
//var str = "D:"+token[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4];
alert("D:"+tokens[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4]);
You can do with substr but for this you have to find index of letters. So Spit with regex is simpler approach.

So I took #chandil03's answer and tweaked it to return a HH:MM:SS format.
var stamp = "PT2H10M13S"
// strip away the PT
stamp = stamp.split("PT")[1];
// split at every character
var tokens = stamp.split(/[A-Z]+/);
// If there are any parts of the time missing fill in with an empty string.
// e.g "13S" we want ["", "", "13", ""]
for(var i = 0; i < 4 - stamp.length; i++){
tokens.unshift("");
}
// Here we add logic to pad the values that need a 0 prepended.
var stampFinal = tokens.map(function(t){
if(t.length < 2){
if(!isNaN(Number(t))){
return ("0" + Number(t).toString());
}
}
return t;
});
// pop the last element because it is an extra.
stampFinal.pop();
console.log(stampFinal.join(":"));

I found this page:
http://www.petershev.com/blog/net-timespans-returned-by-breeze-js-or-working-with-iso8601-duration-standard/
So when I added to https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js this js,
I can convert
duration = moment.duration.fromIsoduration('P18DT5H2M3S');
duration._data can be used
it has _days, _hours, _minutes

Please, find my solution based on inoabrian's.
function fromString(timeSpan) {
var hours = 0;
var minutes = 0;
var seconds = 0;
if (timeSpan != null && typeof (timeSpan) == 'string' && timeSpan.indexOf('PT') > -1) {
timeSpan = timeSpan.split("PT")[1].toLowerCase();
var hourIndex = timeSpan.indexOf('h');
if (hourIndex > -1)
{
hours = parseInt(timeSpan.slice(0, hourIndex));
timeSpan = timeSpan.substring(hourIndex + 1);
}
var minuteIndex = timeSpan.indexOf('m');
if (minuteIndex > -1)
{
minutes = parseInt(timeSpan.slice(0, minuteIndex));
timeSpan = timeSpan.substring(minuteIndex + 1);
}
var secondIndex = timeSpan.indexOf('s');
if (secondIndex > -1)
seconds = parseInt(timeSpan.slice(0, secondIndex));
}
return [hours, minutes, seconds];
}

Related

Generate random string every 24 hours then refresh JavaScript?

What I have been trying to make may be a bit more complicated than I thought.
So what I am trying to accomplish is... generating a random string of characters through javascript (which I have the code for) but only generating a new one at 12am or every 24hrs.
The code I have should work (doesn't) and that's what I need help with.
<div id="password1">
</div>
<script>
var d = new Date();
var n = d.getDay();
var passwords = [makeid(10)[n]]; //want it to be 10... stay the same characters for 24hrs then change
document.getElementById("password1").innerHTML = passwords[n];
function makeid(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
</script>
Is it possible with javascript or not, is it a simple solution or syntax error? I have no idea...
I looked in to this and couldn't find any similar posts...
Since you have coded your own password generator, I used your code to make a new password string lasting for 24 hours unless the localStorage gets cleard.
Cookie can be used too but localStorage and Cookie both are not properly runnable through sandbox environments, so try this on your own development environment. Please note that storing private values like passwords is not good for the security.
<div id="password1">
</div>
<script>
function makeid(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
const key = "keyForTheVulnurablePassword";
if(localStorage.getItem(key) == null) {
let expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
localStorage.setItem(key, JSON.stringify({pw:makeid(10), expire:expireDate}));
}
else {
let currentDate = new Date();
let storedExpireDate = new Date(JSON.parse(localStorage.getItem(key)).expire);
if(storedExpireDate <= currentDate) {
while(storedExpireDate <= currentDate) {
storedExpireDate.setDate(storedExpireDate.getDate() + 1);
}
localStorage.setItem(key, JSON.stringify({pw:makeid(10), expire:storedExpireDate}));
}
}
document.getElementById("password1").innerHTML = JSON.parse(localStorage.getItem(key)).pw;
</script>
<div id="password1">
</div>
<script>
function execute(){
var d = new Date();
var n = d.getDay();
var passwords = [makeid(10)[n]]; //want it to be 10... stay the same characters for 24hrs then change
document.getElementById("password1").innerHTML = passwords[n];
}
function makeid(length) {
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
const milisecondsUntil12Pm = 1000 // Write here the number of Miliseconds until 12 pm at the timeof run this script
setTimeout(()=> {
execute()
setInterval(()=> {
execute()
}, 86400000) // 24 hours * 60 minutes * 60 seconds * 1000 miliseconds = 86400000 Miliseconds
}, milisecondsUntil12Pm)
</script>

Im having trouble with Month comparison in JS

I am trying to compare months from a form, which are 1,2,3,4,5,6,7,8,9,10,11,12 to getMonth()
I have been trying to figure it out for a while, and tried parsing to Int and making sure the Int's
are the same, i.e. single digits, but to no effect.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth"));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear"));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
The year comparison works fine, but the second if statement will not work for some reason unknown to me.
you need to check year, cardYear, cardMonth & month first !
for this you have to log all these variables.
and you did not get the value of these two given lines
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var cardYear = parseInt(document.getElementById("cardyear").value));
now you can try this code and let me if its work fine.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear").value));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
console.log(`${year} === ${cardYear} && ${cardMonth} < ${month}`)
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
I fixed it by changing the html value properties. It was reading the value and not what was between the tags as I had thought.
I tried using this:
var demo = document.getElementById("demo");
demo.innerHTML=month+" "+cardMonth+" "+year+" "+cardYear;
To print the values and troubleshooted as I don't have breakpoints in notepad++.
Thanks for giving me the idea.

Incrementing alphabet from a specific input

I am new to JavaScript. Here is my task
I want to generate a Serial number starting with 'A' and with numbers in increment manner.
Example : A000001, A000002,...,A000010 and so on.
I want to generate this serial number according to the current year I am giving as an input.
Example :
If current year is 2020, then A000001, A000002,...,A000010 and so on
If current year is 2021, then B000001, B000002,...,B000010 and so on
If current year is 2046, then it should be like AA000001, AA000002,...,AA000010 and so on . Because 26 letters, it should start from AA. Same way for 2047 - AB, 2048 - AC and so on.
function colName(n) {
var ordA = 'A'.charCodeAt(0);
var ordZ = 'Z'.charCodeAt(0);
var len = ordZ - ordA + 1;
var year = 2020;
var s = "";
while(n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
Here I have a code that will generate alphabets in the manner of A,B,C,....Z,AA. But when I call the function colName(n), the value of 'n' should be given from 0 to start from 'A'. I want to give the value as my current year. If I give n value 2020, then it should show 'A'.
I am stuck here and not getting idea about how to do this and how to add incrementing number with this. Here I am giving an image of my concept
Thank you.
You need to subtract n by 2020, to make it starting point (think of it as offset).
Also 2027 will be H not AA, since 2020=A, and 26 characters from there will be Z.
function colName(n) {
var ordA = 'A'.charCodeAt(0);
var ordZ = 'Z'.charCodeAt(0);
var len = ordZ - ordA + 1;
n -= 2020;
var s = "";
while(n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
document.write(colName(2020));

Change Date format from one format to another in Java Script

Date can be in any format 25.10.2018 or 25.10.18 or 25-12-2018 or 25-12-18, need to change this date to 25/10/2018 this format only.
The user can input date in any above format, I need to distinguish first in which format then needs to change its format to the desired format.
I do not want to use any 3rd Party JavaScript file.
You can easily do this using momentjs.
Check below working examples:
let d1 = "25.10.2018";
console.log(moment(d1, "DD.MM.YYYY").format("DD/MM/YYYY"));
let d2 = "25.10.18";
console.log(moment(d2, "DD.MM.YY").format("DD/MM/YYYY"));
let d3 = "25-12-2018";
console.log(moment(d3, "DD-MM-YYYY").format("DD/MM/YYYY"));
let d4 = "25-12-18";
console.log(moment(d4, "DD-MM-YY").format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
So your original date have included special character like .,- .So you can split with that characters and I add 0 for your month and date 1 digit.For year format , use new Date to get correct year even two digit have provided ....
var d = '12-4-88'; // '25.10.2018'; or 25.10.18 or 25-12-2018
d = d.split(/[.\-_]/);
d.forEach((v,k) => {
if(v < 10) d[k] = 0 + v;
if(k == 2 && v.length == 2) {
var year = new Date(v+"-01-01");
d[k] = year.getFullYear();
}
})
console.log(d[0] + '/' + d[1] + '/' + d[2]);
You will need Date to preserve full year as two digits year value evaluates invalid date.
function parse(str) {
var result = {
'input': str,
'output': null
};
var tmp = str.split(/[\.|\-]/);
if (tmp && 3 === tmp.length) {
if (2 === tmp[2].length) {
tmp[2] = new Date().getFullYear().toString().substr(0, 2) + tmp[2];
}
if (1 === tmp[1].length) {
tmp[1] = '0' + tmp[1];
}
result.output = tmp.join('/');
}
return result;
}
console.log(parse("25.10.2018"));
console.log(parse("25.10.18"));
console.log(parse("25-10-2018"));
console.log(parse("25-10-18"));
console.log(parse("25.1.2018"));
console.log(parse("05.10.2018"));
function replaceAll(string, search, replacement) {
return string.replace(new RegExp(search, 'g'), replacement);
};
const newDate = replaceAll(oldDate, '.', '/');
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
"25.10.2018".replaceAll(".", "/");

Get the next highest date value after excluding values from an array

I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1

Categories

Resources