How to change date format using jQuery?
Asked Answered
H

5

22

I have a date in a format like this fecha2.value = '2014-01-06', but I want to change the format to this '01-06-14' using jQuery.

How can I do this?

Hanover answered 6/1, 2014 at 9:9 Comment(2)
jQuery doesn't have any date-specific functions. It looks like you should be able to do this just using simple Javascript string operations. What part are you having trouble with?Pneumatology
https://mcmap.net/q/127105/-jquery-date-formattingHypothesis
M
63

You can use date.js to achieve this:

var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

Alternatively, you can do it natively like this:

var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);

console.log(newDate);
Mcgee answered 6/1, 2014 at 9:11 Comment(3)
how can we do this on a plane javascript?Siddons
The second example is using plain JavascriptMcgee
I would use split if you can. I just had an issue with days and months getting mixed up.Incogitable
M
7
var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

Mordant answered 6/1, 2014 at 9:28 Comment(0)
P
6

You don't need any date-specific functions for this, it's just string manipulation:

var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);
Pneumatology answered 6/1, 2014 at 9:14 Comment(0)
R
6

I dont think you need to use jQuery at all, just simple JavaScript...

Save the date as a string:

dte = fecha.value;//2014-01-06

Split the string to get the day, month & year values...

dteSplit = dte.split("-");
yr = dteSplit[0][2] + dteSplit[0][3]; //special yr format, take last 2 digits
month = dteSplit[1];
day = dteSplit[2];

Rejoin into final date string:

finalDate = month+"-"+day+"-"+year
Replace answered 6/1, 2014 at 9:16 Comment(0)
B
1

In most projects you want to use moment.js library along with datepicker and datetimepickers .

It doesnt look that verbose. For example

let dateString_ = moment('2023-01-17T13:39:48.530801Z').format("YYYY-MM-DD HH:mm");

for 2023-01-17 18:39

Formatting rules are here

Brazen answered 17/1, 2023 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.