1

I am new to javascript, i am getting date from query, but i want change another formate

$('#example1').DataTable({
         "ajax": {
            "url": "/txnlist/data",
            "data": {"date":[[${date}]]},
            "dataSrc": ""
        },

        "columns": [
            { "data": "id" },
            { "data": "AccountNumber" },
            { "data": "TransactionDate"} // date:032716
        ],
});

here i am getting date mmddyy,but i want yyyy-dd-mm. How to change it?

3

2 Answers 2

1

You can use the following code as an example:

var yourDate = '032716'; //mmddyy
// keep in mind that 16 is ambiguous as it could be either 1916 or 2016 so parse it properly
var year = '20' + yourDate.substring(4, 6);
var month = yourDate.substring(0, 2);
var day = yourDate.substring(2, 4);
// pass params as yy mm dd
var dateObj = new Date(year, month, day);

var parsedDateObj = dateObj.getFullYear() + '-' + month + '-' + day; // yyyy-dd-mm
console.log(parsedDateObj); // output: 2016-03-27

Try it online on jsfiddle.

Alternatively if you don't mind using a library for that you could use moment js and format it like this:

moment(dateObj).format('YYYY-MM-DD');
Sign up to request clarification or add additional context in comments.

5 Comments

"TypeError: yourDate.substring is not a function" i am getting
@Durga Is your date 032716 an integer or a string? If it is an integer make sure that you pass it as a string.
Finally i am getting output but 209-32-91 my original date is 032917
@Durga make sure to pass the correct value as string to 'yourDate' variable. Add a console.log and check if the value you pass is correct, casting to string as 032716.toString() will return "13774" which is not the value you want. Check the link with the online example I have added.
Thanks a lot for your help, you saved my day
1

You are a beginner so think it simple. if you go with custom functions you will get confused.

try to use moment.js a timezone js library.

check my answer how i did using moment.js

for your easy understand will split it further,

my_date_format = "032716" // your date in MM(Month)DD(date)YY(2 digit year format)
my_date = moment(my_date_format, "MM-DD-YY") // getting moment date based on your format. here, date is your input date and exisitng format you have
new_date = my_date.format("YYYY-MM-DD") // date you want to format  
console.log(new_date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.1/moment.js"></script>
<div id="example1"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.