Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

android - Javascript date is invalid on iOS

I'm working on a Phonegap-based iOS app, which is already done for Android. The following lines are working fine for Android but not for iOS. Why?

var d = new Date("2015-12-31 00:00:00");
console.log(d.getDate() + '. ' + d.getMonth() + ' ' + d.getFullYear();

Result for Android:

31.11 2015

Result on iOS:

NaN. NaN NaN

Where is the difference coming from?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your date string is not in a format specified to work with new Date. The only format in the spec is a simplified version of ISO-8601, added in ES5 (2009). Your string isn't in that format, but it's really close. It would also be easy to change it to a format that isn't in the spec, but is universally supported

Four options for you:

  • Use the upcoming Temporal feature (it's now at Stage?3)
  • The specified format
  • An unspecified format that's near-universally supported
  • Parse it yourself

Use the upcoming Temporal feature

The Temporal proposal is at Stage?3 as of this update in August 2021. You can use it to parse your string, either treating it as UTC or as local time:

Treating the string as UTC:

// (Getting the polyfill)
const {Temporal} = temporal;

const dateString = "2015-12-31 00:00:00";
const instant = Temporal.Instant.from(dateString.replace(" ", "T") + "Z");
// Either use the Temporal.Instant directly:
console.log(instant.toLocaleString());
// ...or get a Date object:
const dt = new Date(instant.epochMilliseconds);
console.log(dt.toString());
<script src="https://unpkg.com/@js-temporal/polyfill/dist/index.umd.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...