0

Hi I am developing web application in angularjs. I have one date in angularjs for example 13-10-2017. In c# i have below field

 public DateTime LicenseExpiryDate { get; set; }

When i send 13-10-2017 in ajax request,LicenseExpiryDate accepts as 0001-01-01. May i know how to fix this? I can see my angular date is in dd-mm-yy format and c# date default format is yyyy-mm-dd. i tried to convert it to yyyy-mm-dd as below

 function formatDateDOsetyymmdd(date) {
                debugger;
                var d = new Date(date),
                    month = '' + (d.getMonth() + 1),
                    day = '' + d.getDate(),
                    year = d.getFullYear();

                if (month.length < 2) month = '0' + month;
                if (day.length < 2) day = '0' + day;

                return [year,month, day].join('-');
            }

and this returns NaN-NaN-NaN Any help would be appreciated. Thank you.

10
  • works fine with the right input ... how are you calling it? (and which browser?) Commented Sep 12, 2017 at 6:28
  • Thank you. I am accessing as $scope.modelname. Commented Sep 12, 2017 at 6:29
  • yeah, that shows exactly how you are calling the javascript function in your question Commented Sep 12, 2017 at 6:30
  • So how should i access it? Commented Sep 12, 2017 at 6:30
  • you're debugging it, right? ... what is the value of date when you're debugging Commented Sep 12, 2017 at 6:31

2 Answers 2

1

You are getting a string in form dd-mm-yyyy on input, what you want to do is turn that string into three numbers, and use those in the new Date call

function formatDateDOsetyymmdd(date) {
    date = date.split('-').map(Number);
    var d = new Date(date[2], date[1] - 1, date[0]),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year,month, day].join('-');
}
console.log(formatDateDOsetyymmdd('13-10-2017'));

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I am getting date in server side but problem is i selected 13-10-2017 but when i convert using formatDateDOsetyymmdd it became 2016-10-01. something wrong in above function?
Of course it did, I hardly ever post buggy answers :p (ok, I do it more often than I care to admit)
0

you can use moment.js , if you can't do this in JavaScript means you can use it.

https://momentjs.com/

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.