Problems formatting a String on date

1

My problem is that I receive a String element from my form, which can be of these two formats:

fecha = "010117";

or

fecha = "01012017";

And I need to format them to a date format valid as "01/01/2017" , I've tried to do it in several ways, including this one:

var newfecha = new Date( fecha.replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );

But do not do it correctly, could someone give me any suggestions?

    
asked by Piliopan 05.01.2017 в 08:58
source

3 answers

2

I'll give you an example in javascript in case it helps you.

alert(checkDate('010117'));
alert(checkDate('01012017'));

function checkDate(myFecha){
    var ret = "error";
    //pasa la expresion regular
    var m = myFecha.match(/^(\d{2})(\d{2})(\d{2,4})$/);
    if(m==null){
        alert('la fecha no es valida');
    } else {
        //si vienen sólo 2 digitos en año asumo que es el año 2000
        if(m[3].length==2){
            m[3] = '20' + m[3];
        }
        try {
            //usa la funcion toISOString para comprobar que la fecha es válida
            new Date(m[3] + '-' + m[2] + '-' + m[1]).toISOString();     
            ret = m[1] + '-' + m[2] + '-' + m[3];
        }
        catch(err) {
            alert('la fecha no es valida');
        }   
    }
    return ret;
}
    
answered by 05.01.2017 / 10:21
source
0

You could use a SimpleDataFormat:

SimpleDateFormat formato;  
    if(fecha.length==6)
        formato = new SimpleDateFormat("MMddyy");
    else
        formato = new SimpleDateFormat("MMddyyyy");

        try {
            Date date = formato.parse(fecha);
             System.out.println(date);
             //Fecha con formato dd-MM-yyyy
             System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(date));
        } catch (ParseException ex) {
            //
        }

Greetings,

    
answered by 05.01.2017 в 09:23
0

Try this line:

fecha.replace(/(\d{2})(\d{2})(\d+)/, function(s, d, m, a){ 
    return [d, m, a.length === 2 ? "20" + a : a].join("/")
});

The purpose is to separate the (4 or 2) (\ d +) last numbers, then prefix 20 if in case it has 2 digits.

//var fecha = "01012017";
var fecha = "010117";

var newFecha = fecha.replace(/(\d{2})(\d{2})(\d+)/, function(s, d, m, a){ 
	return [d, m, a.length === 2 ? "20" + a : a].join("/")
});

console.log(newFecha); //01/01/2017
    
answered by 05.01.2017 в 10:20