convert time stamp to Date inside angular expression like {{new Date(timestamp)}}
Because angular expressions do not accept arbitrary Javascript code, including creating new objects. What you are looking for is called angular filters, they were specifically designed for this case.
So instead of
{{new Date(elem.timestamp)}}
you should write
{{elem.timestamp | date: 'yyyy-MM-dd'}}
More info on the date filter can be found here. More on filters, in general, can be found here.
Convert timestamp to date using Angular 2 pipes
As mentioned by @Perry you will need to provide the date in milliseconds. From the Angular 2 reference for date we have:
expression is a date object or a number (milliseconds since UTC epoch)
or an ISO string
So it can be simply be:
{{load.loadDate * 1000 | date}}
How do you get a timestamp in JavaScript?
Short & Snazzy:+ new Date()
A unary operator like plus
triggers the valueOf
method in the Date
object and it returns the timestamp (without any alteration).
Details:
On almost all current browsers you can use Date.now()
to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).
You can easily make a shim for this, though:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
To get the timestamp in seconds, you can use:
Math.floor(Date.now() / 1000)
Or alternatively you could use:
Date.now() / 1000 | 0
Which should be slightly faster, but also less readable.
(also see this answer or this with further explaination to bitwise operators).
I would recommend using Date.now()
(with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date
object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:
new Date().getTime()
Which you can then convert to seconds like this:
Math.round(new Date().getTime()/1000)
And you can also use the valueOf
method which we showed above:
new Date().valueOf()
Timestamp in Milliseconds
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();
console.log(timeStampInMs, Date.now());
Find a time slot which can accommodate a new time stamp and calculate frequency
You can assign the index to a particular time slot. Then we can convert an incoming time to the index.
An index could be calculated by how many "slots" proceeds the particular time, sou we could divide the time in minutes by 15 to get the index.
[
"00:00-00:15", // 0th -> index = 0
"00:15-00:30", // 1st -> index = 1
.
.
.
"11:15-11:30", // 93th
"11:30-11:45", // 94th
"11:45-00:00" // 95th -> index = 95
]
const indexToTime = (index) => {
const hour = Math.floor(15 * index / 60) % 24
const minute = (15 * index) % 60
const h = `${hour}`.padStart(2, 0)
const m = `${minute}`.padStart(2, 0)
const time = `${h}:${m}`
return time
}
const timeToIndex = (time) => {
const [hour, minute] = time.split(':')
const [h, m] = [parseInt(hour), parseInt(minute)]
const index = hour * 4 + Math.floor(minute / 15)
return index
}
const slots = [...Array(24 * 60 / 15)].map((_, i) => `${indexToTime(i)}-${indexToTime(i+1)}`)
console.log('slots =', slots)
const records = ['20:47 apple', '20:18 apple', '20:17 bananas', '20:43 cake', '20:18 bananas', '20:31 cake', '20:30 cake', '20:40 cake', '20:39 cake', '20:49 apple', '20:54 egg', '20:50 apple']
console.log('records =', records)
const stats = []
records.forEach(record => {
const [time, item] = record.split(' ')
const index = timeToIndex(time)
if (!stats[index]) {
stats[index] = {[item]: 1}
} else if(!stats[index][item]) {
stats[index][item] = 1
} else {
stats[index][item]++
}
})
console.log('stats =', stats)
const statsRecords = slots.map((time, index) => ({ time, stats: stats[index] }))
console.log('statsRecords =', statsRecords)
const display = (statsRecords) => {
return statsRecords.map(({ time, stats = {} }) => `${time} ${Object.entries(stats).map(([item, count]) => `${item} ${count}`).join(', ')}`).join('\n')
}
console.log(display(statsRecords))
How to reverse time stamp using javascript/Angular.js
You are using angular. So please try with using $filter
$scope.timestamp = '2016-12-16 07:02:15 am'
$scope.originalStamp = $filter('date')
(new Date($scope.timestamp.replace("-","/")),'dd-MM-yyyy HH:mm:ss a');
Updated Demohere is the full code
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="datCtrl">
<p> {{originalStamp}} </p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope,$filter) {
$scope.timestamp = '2016-12-16 07:02:15 am'
$scope.originalStamp = $filter('date')(new Date($scope.timestamp.replace("-","/")),'dd-MM-yyyy HH:mm:ss a');
});
</script>
<p>The date filter formats a date object to a readable format.</p>
</body>
</html>
Format Date time in AngularJS
v.Dt is likely not a Date() object.
See http://jsfiddle.net/southerd/xG2t8/
but in your controller:
scope.v.Dt = Date.parse(scope.v.Dt);
Related Topics
How to Add Class on Specific Div When Scroll
Expected to Return a Value At the End of Arrow Function Array-Callback-Return on Filter Function
How to Open a Url Link from JavaScript Inside a Google Apps Script HTML Google Site Gadget
How to Share and Edit Global Variables Between Two JavaScript Node Runs
How to Change Color of Button on Press in React Native
How to Force Clients to Refresh JavaScript Files
Draw a Connecting Line Between Two Elements
How to Hide the Parent Div If All Its Child Div Are Hidden
How to Add a Dynamic Action That Will Redirect to Another Page by Executing JavaScript Code
How to Delete a Localstorage Item When the Browser Window/Tab Is Closed
Webpack: Module Not Found: Error: Can't Resolve (With Relative Path)
How to Change the Font Color, Font Size, and Button Color in React
Split a String Only the At the First N Occurrences of a Delimiter
Creating a Leaderboard in Html/Js
Regex to Allow Only Certain Special Characters and Restrict Underscore
How to Disable Print-Screen Functionality for a Webpage in All Browsers
Way to Access Const from Another Component in React
How to Only Trigger Parent Click Event When a Child Is Clicked