user6161224
user6161224

Reputation:

change date format in javascript

I have date format like dd.mm.yyyy

24.1.2017 00:00:00

as result I want

2017/01/24

I wrote this function to change date to format what I want.

 Date.prototype.yyyymmdd = function() {
                var mm = this.getMonth() + 1; // getMonth() is zero-based
                var dd = this.getDate();

                return [this.getFullYear(),
                        (mm>9 ? '' : '0') + mm,
                        (dd>9 ? '' : '0') + dd
                ].join('/');
            };

            var date = new Date("@Model.BeginTime");

            $("#newsstart").val(date.yyyymmdd());

Problem is to convert string to date

var date = new Date("@Model.BeginTime");

This is invalid date. How can I fix this problem??

Upvotes: 2

Views: 5620

Answers (3)

RobG
RobG

Reputation: 147373

Problem is to convert string to date

var date = new Date("@Model.BeginTime");

Your problem is that you are using the Date constructor to parse a string, which is not recommended. Parsing using the Date constructor (and Date.parse, they are equivalent for parsing) is largely implementation dependent and unreliable. You should use a small function or library to parse it to a date.

Since you're happy to extend Date.prototype with a format function, you could also extend String.prototype with an equivalent parse, e.g.

String.prototype.parseYMD = function() {
  var b = this.split(/\D/);
  return new Date(b[0], b[1]-1, b[2]);
}

console.log('2017/01/21'.parseYMD().toString());

Or you could use a small library like fecha.js:

var date = fecha.parse('2017/01/24','YYYY/MM/DD');

PS

The specific problem here is that your string is similar to ISO 8601 but not similar enough for some browsers. Some will think it's invalid ISO 8601 and return an invalid date, others will think it's not ISO 8601 and parse it to a date for 24 January, 2017. Both results can be considered correct according to the ECMAScript language specification.

Upvotes: 0

Moment is the js to use :)

Doesnt accept 24.1.2017 00:00:00 format

that is because you are implementing the class wrong or using an invalid format..

By inspecting your code I see that this here 24.1.2017 00:00:00 is not matching this pattern dd.mm.yyyy

2017/01/24 is with the pattern yyyy/MM/DD formatted

here a piece of code that can illustrate better:)

var res1 = $("#result"); 

var dateForm = moment('24.1.2017 00:00:00','DD.M.YYYY hh:mm:ss').format('YYYY/MM/DD')
res1.text(dateForm);

 
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<div id="result"></div>
 

Upvotes: 1

Harkirat Saluja
Harkirat Saluja

Reputation: 8114

You can use moment library to do convert UTC to formats you want.

You can somewhat like following moment(date).format("YYYY-MM-DD");

Upvotes: 1

Related Questions