Why Does This Happen?
This TypeScript error is shown because the Date.prototype.toGMTString()
method was deprecated in ES3:
const dt = new Date('14 Jan 2024 00:00:00 PDT');
// Property toGMTString does not exist on type Date
console.log(dt.toGMTString())
Even though TypeScript complains, the Date.prototype.toGMTString()
method remains implemented in browsers for backward compatibility reasons, which means that this code will still work. However, you should avoid using it.
How to Fix the Issue?
The Date.prototype.toGMTString()
method exists as an alias to the Date.prototype.toUTCString()
method. In fact, both methods point to the exact same function object:
Date.prototype.toGMTString === Date.prototype.toUTCString // true
Therefore, to fix this issue you can simply use the Date.prototype.toUTCString()
method instead:
const dt = new Date('14 Jan 2024 00:00:00 PDT');
console.log(dt.toUTCString()); // 'Sun, 14 Jan 2024 07:00:00 GMT'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.