Question User
Question User

Reputation: 99

convert my date to timestamp in javascript

How to convert my date to timestamp i dont know where im doing wrong.Any suggestion please ?

var dates = '27-04-2015';
var date1 = new Date(dates).getTime();
alert(date1);

Upvotes: 3

Views: 15149

Answers (2)

user2575725
user2575725

Reputation:

Date constructor takes argument in mm-dd-yyyy format, try this

var timeStamp = function(str) {
  return new Date(str.replace(/^(\d{2}\-)(\d{2}\-)(\d{4})$/,
    '$2$1$3')).getTime();
};
alert(timeStamp('27-04-2015'));

Here, I had used RegExp to swap the format from dd-mm-yyyy to mm-dd-yyyy. So '27-04-2015' gives '04-27-2015'. In the expression (\d{2}\-)(\d{2}\-)(\d{4}), \d denotes integer, {} for length, () for grouping, \ to escape special characters like -.

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15403

Parameter you passed in the new Date('27-04-2015') is not valid. Use sepeartor '/' for change date format and send to the new Date('27/04/2015').

var dates = '27-04-2015';
var dates1 = dates.split("-");
var newDate = dates1[1]+"/"+dates1[0]+"/"+dates1[2];
alert(new Date(newDate).getTime());

Working Fiddle

Upvotes: 6

Related Questions