0

so really sorry if this question seems silly. So I went to Typescript Playground and wrote a simple get time code.

Code:

// 1 Week Logic
function get1WeekDate() {
  const now = new Date();

  return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
}

// 2 Week Logic
function get2WeeksDate() {
  const now = new Date();

  return new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);
}

console.log("Current Date:",new Date());

console.log("Last Week Date:",get1WeekDate());

console.log("Last 2 Week Date:",get2WeeksDate());

Output:

[LOG]: "Current Date:",  Date: "2022-05-30T13:19:06.403Z" 
[LOG]: "Last Week Date:",  Date: "2022-05-23T13:19:06.405Z" 
[LOG]: "Last 2 Week Date:",  Date: "2022-05-16T13:19:06.406Z" 

But same code in jsfiddle gave me different result: Jsfiddle output:

"Current Date:", [object Date] { ... }
"Last Week Date:", [object Date] { ... }

When I added the code in angular component and checked result using console.log in Browser DOM Output:

DOM Output

I want to get today's date and 1 week ago and 1 month ago date in timestamp. How can I do it in Typescript I want dates like '2022-05-30T12:30:51.272Z'

Cpt Kitkat
  • 1,290
  • 2
  • 26
  • 47
  • Your code has no TypeScript at all. Btw I didn't understand if your problem is on the format of the console or the `Date` objects contain different date values – Cristian Traìna May 30 '22 at 14:02

1 Answers1

1

--EDIT--

As @adiga correctly states:

currentdate.toISOString(); 

If you want a more elaborate way:


I've searched for it myself some time ago and it seems not available, with help of StackOverflow I eventually came to this function:

  // Get a proper formatted timestamp.
  static getTimeStamp(): string {
    let currentdate = new Date();
    let timestamp =  currentdate.getUTCFullYear() + "-" +
      ("0" + (currentdate.getUTCMonth() + 1)).slice(-2) + "-" +
      ("0" + currentdate.getUTCDate()).slice(-2) + "T" +
      ("0" + currentdate.getUTCHours()).slice(-2) + ":" +
      ("0" + currentdate.getUTCMinutes()).slice(-2) + ":" +
      ("0" + currentdate.getUTCSeconds()).slice(-2) + "." +
      ("000000" + currentdate.getMilliseconds()).slice(-6) + "Z";
    console.log("Generated TimeStamp",timestamp);
    return timestamp;

  }

In your case you have to limit the milliseconds to 3 digits.

Charlie V
  • 319
  • 2
  • 9
  • 1
    How is this different to `currentdate.toISOString()`? – adiga May 30 '22 at 14:22
  • hmmm, yours is less code.... checked the working and better results... I've no idea why this didn't work (and now does....) I'll add it to the answer. – Charlie V May 30 '22 at 15:09