Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

clayton-mer

Problema em gerar data fixa

Recommended Posts

boa noite equipe do forum hj me deparei com a seguinte dúvida estou gerando parcelas em java script em um formulário e estou com o a seguinte dúvida preciso gerar parcelas com vencimento fixo tipo 1ª 21/07/2014, 2ª 21/08/2014, 3ª 21/09/2014 tenho um código que gera as data somando dias em uma data.

// Função Validar Data
function numdias(mes,ano) {
   if((mes<8 && mes%2==1) || (mes>7 && mes%2==0)) return 31;
   if(mes!=2) return 30;
   if(ano%4==0) return 29;
   return 28;
}

function somadias(data, dias) {
  data=data.split('/');
  diafuturo=parseInt(data[0])+dias;
  mes=parseInt(data[1]);
  ano=parseInt(data[2]);
  
  while(
  diafuturo>numdias(mes,ano)){
	  diafuturo-=numdias(mes,ano);
		  mes++;
		  
		  if(mes>12){
			 mes=1;
			 ano++;
	 	  }
  }

  if(diafuturo<10) diafuturo='0'+diafuturo;
  if(mes<10) mes='0'+mes;

  return diafuturo+"/"+mes+"/"+ano;
}

até ai tudo bem essa função acima gera certinho as datas somando 30 dias, mais o problema que dai não fica todos com o mesmo vencimento.

 

eu tentei fazer assim, onde retorna da data pronta um mudei para a variável data[0] que é o dia.

retorno
return diafuturo+"/"+mes+"/"+ano;

auterei por
return data[0]+"/"+mes+"/"+ano;

ele até retorna a data certa mais dai não funciona a validade tipo se digitar um data exemplo 29, 30 e 31 ele não validade porque tem meses que não tem.

ex.

mostrar 31/08/2014, 31/09/2014, 31/10/2014 ..... 31/02/2015, gostaria de corrigir esse bug.

 

então preciso da ajuda de vocês para fazer um função que some dias em uma data mais que valide essa data caso não exista a data ela mudar para próxima data validade.

 

 

desde de já muito obrigado.

 

att

Clayton

 

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Eu estava fazendo isso esses dias, A lógica é o seguinte: você tem que calcular o último dia do mês para validar, eu prefiro manipular as datas com o formato Date do javascript, segue uma classe para isso:

DateService = (function() {
  function DateService() {}
 
  DateService.prototype.createFromFormat = function(format, str) {
    var c, date, day, grupo_n, grupos, hour, i, minute, month, re, regexStr, rs, second, year, year_now, year_two;
    if (typeof str !== "string") {
      console.log("str must be string in createFromFormat");
      return false;
    }
    grupos = {};
    grupo_n = 0;
    regexStr = "^";
    i = 0;
    while (i < format.length) {
      c = format[i];
      switch (c) {
        case "d":
          regexStr += "([0-9]{2})";
          grupos["day"] = ++grupo_n;
          break;
        case "m":
          regexStr += "([0-9]{2})";
          grupos["month"] = ++grupo_n;
          break;
        case "Y":
          regexStr += "([0-9]{4})";
          grupos["year"] = ++grupo_n;
          break;
        case "y":
          regexStr += "([0-9]{2})";
          grupos["year_two"] = ++grupo_n;
          break;
        case "H":
          regexStr += "([0-9]{2})";
          grupos["hour"] = ++grupo_n;
          break;
        case "i":
          regexStr += "([0-9]{2})";
          grupos["minute"] = ++grupo_n;
          break;
        case "s":
          regexStr += "([0-9]{2})";
          grupos["second"] = ++grupo_n;
          break;
        default:
          regexStr += (c + "").replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
      }
      i++;
    }
    regexStr += "$";
    re = new RegExp(regexStr);
    rs = str.match(re);
    if (!rs) {
      return false;
    }
    if (typeof grupos["year"] === "undefined" && typeof grupos["year_two"] === "undefined") {
      return false;
    }
    year = null;
    month = null;
    day = null;
    hour = null;
    minute = null;
    second = null;
    if (typeof grupos["year"] !== "undefined") {
      year = Number(rs[grupos["year"]]);
    }
    if (typeof grupos["year_two"] !== "undefined") {
      year_two = Number(rs[grupos["year_two"]]);
      year_now = (new Date()).getFullYear();
      if (year_two > 50 && year_now < 2040) {
        year = Number("19" + String(year_two));
      } else {
        year = Number("20" + String(year_two));
      }
    }
    if (typeof grupos["month"] !== "undefined") {
      month = Number(String(rs[grupos["month"]]));
    }
    if (typeof grupos["day"] !== "undefined") {
      day = Number(String(rs[grupos["day"]]));
    }
    if (typeof grupos["hour"] !== "undefined") {
      hour = Number(rs[grupos["hour"]]);
    }
    if (typeof grupos["minute"] !== "undefined") {
      minute = Number(rs[grupos["minute"]]);
    }
    if (typeof grupos["second"] !== "undefined") {
      second = Number(rs[grupos["second"]]);
    }
    date = new Date(year, (month ? month - 1 : month), day, hour, minute, second);
    if (date) {
      return date;
    } else {
      return false;
    }
  };
 
  DateService.prototype.format = function(format, date) {
    var day, hour, minute, month, r, re, resp, second, year;
    if (typeof date === "undefined") {
      date = new Date();
    }
    if (!date) {
      return false;
    }
    day = date.getDate();
    month = date.getMonth() + 1;
    year = date.getFullYear();
    hour = date.getHours();
    minute = date.getMinutes();
    second = date.getSeconds();
    r = {
      "(^|[^\\\\])d": (day <= 9 ? "0" + day : String(day)),
      "(^|[^\\\\])m": (month <= 9 ? "0" + month : String(month)),
      "(^|[^\\\\])Y": String(year),
      "(^|[^\\\\])H": (hour <= 9 ? "0" + hour : String(hour)),
      "(^|[^\\\\])i": (minute <= 9 ? "0" + minute : String(minute)),
      "(^|[^\\\\])s": (second <= 9 ? "0" + second : String(second))
    };
    resp = format;
    for (re in r) {
      resp = resp.replace(new RegExp(re, "g"), "$1" + r[re]);
    }
    return resp;
  };
 
  DateService.prototype.addMonth = function(dateObj, months) {
    var actualDay, bestDay;
    if (months == null) {
      months = 1;
    }
    months = Number(months);
    actualDay = this.getDay(dateObj);
    dateObj.setDate(1);
    dateObj.setMonth(dateObj.getMonth() + months);
    bestDay = Math.min(actualDay, this.getLastDay(dateObj));
    dateObj.setDate(bestDay);
    return dateObj;
  };
 
  DateService.prototype.addDay = function(dateObj, days) {
    if (days == null) {
      days = 1;
    }
    days = Number(days);
    dateObj.setDate(dateObj.getDate() + days);
    return dateObj;
  };
 
  DateService.prototype.setDay = function(dateObj, day) {
    var bestDay;
    day = Number(day);
    bestDay = Math.min(day, this.getLastDay(dateObj));
    return dateObj.setDate(bestDay);
  };
 
  DateService.prototype.getDay = function(dateObj) {
    return dateObj.getDate();
  };
 
  DateService.prototype.getLastDay = function(dateObj) {
    var d;
    d = new Date(dateObj.getYear(), dateObj.getMonth() + 1, 0);
    return d.getDate();
  };
 
  return DateService;
})();

Segue um exemplo na prática, usando esta classe:

var dateService = new DateService();
var dateStr = '05/01/2014';
var dateObj = dateService.createFromFormat('d/m/Y', dateStr); // vamos criar um objeto Date do JavaScript, semelhante a função DateTime::createFromFormat do php
dateService.addMonth(dateObj, 1); // agora o dateObj é igual a 05/02/2014
dateService.setDay(dateObj, 31); // agora o dateObj é igual a 28/02/2014
dateStr = dateService.format('d/m/Y', dateObj); // vamos criar uma string no formato d/m/Y (semelhante a função date do php)
console.log('dateStr => ', dateStr);

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado meu Amigo Anderson.

 

estou realizando os teste aqui mais ele não está gerando os vencimento vou postar abaixo como estou utilizando a sua função:

//fora do for eu chamo as variáveis e a data inicial
var dateService = new DateService();
var dateStr = '30/10/2014';
var dateObj = dateService.createFromFormat('d/m/Y', dateStr); 
dateService.addMonth(dateObj, 1); 

//inicia o for
for (var iterator = 0; iterator < $(this).val(); iterator++) {

// aqui tenho minha variavel dias_vencimento que por padrão é 0 mais ela soma com o prazo_dias que é 30.
dias_vecimento = dias_vecimento + prazo_dias;

//aqui chamo sua função dentro do for que gera as parcelas
dateService.setDay(dateObj, dias_vecimento); 
dateStr = dateService.format('d/m/Y', dateObj);

// aqui é o append para gerar o input estou imprimindo a variavel dateStr  dentro do value
$("#Linha_Parcela").append('<tr>\
	  <td><input type="text" name="vencimento_parcela[]" value="'+ dateStr +'" onclick="Mascaras()" class="hasDatepicker" required /></td>\	  
	  </tr>'
);



print de como está gerando:

tela_parcelamento.jpg

 

O problema é que ele não soma a quantidade de dias e gera sempre com a data 30/11/2014.

eu quero que ele gere 30/11/2014, 30/12/2014, 30/01/2015, 28/02/2015, 30/03/2015

 

 

para testar se a variável dias_vecimento está gerando corretamente e somando mais 30 dias nela eu estou imprimindo e está somando corretamente.

 

O que tenho que fazer? você pode me ajudar?

 

desde já muito obrigado.

 

Att,

 

Clayton

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.