-1

I currently have the following code:

lastLoginDate = "\/Date(1499994230140+0800)\/";
lastLoginDate = moment(lastLoginDate).format("YYYY-MM-DD hh:mm:ss UTC");
lastLoginDate = new Date(lastLoginDate);

This works in chrome. However when ran in IE, new Date returns invalid date. how do i achieve the same output in IE?

edsamiracle
  • 753
  • 3
  • 12
  • 27
  • You need the format `Tue Dec 05 16:47:20 CDT 2006` -- [_IE JavaScript date parsing error_](https://stackoverflow.com/questions/3020508/ie-javascript-date-parsing-error) – Mr. Polywhirl Jul 14 '17 at 11:31
  • 1
    What on earth is `"\/Date(1499994230140+0800)\/"`? How did you end up with that? – str Jul 14 '17 at 11:45
  • Its being returned by the API – edsamiracle Jul 14 '17 at 11:55
  • What API? If you have access, you should change that and not try to somehow parse it. This format makes absolutely no sense to me. – str Jul 14 '17 at 12:00

3 Answers3

1

resolved my issue by changing format to yyyy/mm/dd instead of yyyy-mm-dd

moment(lastLoginDate).format("YYYY/MM/DD hh:mm:ss UTC");
edsamiracle
  • 753
  • 3
  • 12
  • 27
0

There is no need at all to format and then parse the date again. Just use toDate():

lastLoginDate = moment(lastLoginDate).toDate();

If this does not work, then your lastLoginDate has a wrong format. You can read more about valid formats here.

str
  • 42,689
  • 17
  • 109
  • 127
0

You can split the string into the Unix time and the timezone offset by using a regex.

This code below is easy to follow.

const dateRegex = /^\/Date\((\d+)([-+]\d{4})\)\/$/;
const dateFormat = 'YYYY-MM-DD hh:mm:ss Z';
  
let lastLoginDate = "\/Date(1499994230140+0800)\/";
console.log(parseTimestamp(lastLoginDate));

function parseTimestamp(timestamp) { 
  var groups = dateRegex.exec(timestamp);
  var unixTime = Math.floor(parseInt(groups[1], 10) / 1000);
  var timezoneOffset = groups[2];

  return moment.unix(unixTime).utcOffset(timezoneOffset).format(dateFormat);
}

// Output: 2017-07-14 09:03:50 +08:00
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132