Convert expiration factor (number of days) from ticket to date dd / mm / yyyy

9

I have the following digitable line:

74893.12004 21627.007186 37931.981056 7 60750000001400

As I've already seen in this question, I found out how to calculate maturity mathematically:

Extract Digitable Line Maturity

I need the JS equivalent, which is to extract the expiration factor (first four characters from the last block, in the example above 6075), and add this number to date 7/10/1997 (date 7 October 1997 is always this, basis of all the standard Febraban tickets), obtaining the expiration in the format dd / mm / yyyy.

Example: For factor 1001 the resulting date must be July 4, 2000.

    
asked by anonymous 29.05.2014 / 21:25

2 answers

6

See if this works for you:

var barra = "74893.12004 21627.007186 37931.981056 7 60750000001400";
var vencimento = barra.slice(40, 44); // captura 6075 
var date = new Date('10/07/1997');
date.setTime(date.getTime() + (vencimento * 24 * 60 * 60 * 1000));

alert(("0" + (date.getDate())).slice(-2) + '/' + ("0" + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear());

Or using 1001 as a factor:

var barra = "74893.12004 21627.007186 37931.981056 7 60750000001400";
var vencimento = 1001;
var date = new Date('10/07/1997');
date.setTime(date.getTime() + (vencimento * 24 * 60 * 60 * 1000));

alert(("0" + (date.getDate())).slice(-2) + '/' + ("0" + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear());

JSFiddle

As well pointed out by @Bernardo Botelho, the above code will probably return the day incorrect if we are in daylight saving time , a way to detect this in JavaScript is described in this article in>).

    
29.05.2014 / 22:42
4

Adding a method to the Date class:

var linhaDigitavel = "74893.12004 21627.007186 37931.981056 7 60750000001400";

var dias = parseInt(linhaDigitavel.substr(40, 4));

Date.prototype.adicionarDias = function(dias) {
    var data = new Date(this.valueOf());
    data.setDate(data.getDate() + dias);
    return data;
};

// Meses são indexados em zero em JavaScript, logo é necessário subtrair 1 do mês desejado.
var dataInicialFebraban = new Date(1997, 10 - 1, 7);

alert(dataInicialFebraban);

alert(dataInicialFebraban.adicionarDias(dias));

// Resultado: 26/05/2014

Link to JSFiddle used: link

As a reference, I'll leave a solution that NOT should be used:

var dias = 6075;
var inicio = new Date(1997, 10 - 1, 7);
var vencimento = new Date();
vencimento.setDate(today.getDate() + dias);
alert(vencimento);
// Resultado (incorreto): 24/12/2030

JSFiddle example incorrect: link

Reference for the same question in Stack Overflow in English: link

    
29.05.2014 / 22:33