Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help with javascript date 1

Status
Not open for further replies.

Disskyz

Programmer
Aug 29, 2018
7
US
I have a timestamp object that looks like this: timestamp = 1430770060000. I want to remove the last 3 numbers which represent miliseconds. Since it is a date object, I can't find a method to remove the miliseconds. I tried to convert the value to a string and then use the slice(0,3) to remove the last 3 numbers and convert the remaining 10 characters back to a date, but had an issue. Can someone please help me understand how I can remove the miliseconds from the date.
 
Have you tried the divide and conquer approach.

Math.floor(timestamp / 100)

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Hi

George said:
Math.floor(timestamp / 100)
Dividing by 100 would move only get rid of the last 2 digits.

Disskyz said:
convert the remaining 10 characters back to a date
As the JavaScript [tt]Date[/tt] objects internally handles dates as milliseconds, you have to use it as is. Rounding it to seconds results a different value so for the [tt]Date[/tt] object a different date.

If is really important for compatibility with other languages' date handling, your best option is to make your own functions to do the handling as you want, maybe as methods of the [tt]Date[/tt] prototype :
JavaScript:
[gray]// declare them[/gray]
Date[teal].[/teal][b]prototype[/b][teal].[/teal]getUnixTime [teal]=[/teal] [b]function[/b][teal]() {[/teal] [b]return[/b] Math[teal].[/teal][COLOR=orange]floor[/color][teal]([/teal][b]this[/b][teal].[/teal][COLOR=orange]getTime[/color][teal]() /[/teal] [purple]1000[/purple][teal]) }[/teal]
Date[teal].[/teal][b]prototype[/b][teal].[/teal]setUnixTime [teal]=[/teal] [b]function[/b][teal]([/teal]time[teal]) {[/teal] [b]return this[/b][teal].[/teal][COLOR=orange]setTime[/color][teal]([/teal]time [teal]*[/teal] [purple]1000[/purple][teal]) }[/teal]

[gray]// use them[/gray]
[b]var[/b] sometime [teal]=[/teal] [b]new[/b] [COLOR=orange]Date[/color][teal]()[/teal]
sometime[teal].[/teal][COLOR=orange]setUnixTime[/color][teal]()[/teal]
console[teal].[/teal][COLOR=orange]log[/color][teal]([/teal]sometime[teal].[/teal][COLOR=orange]getUnixTime[/color][teal]())[/teal]

Feherke.
feherke.github.io
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top