Extracting data from JSON file shows /Date(1435837792000+0000)/
How can I format the date to appear as Oct 29, 2010 9:10:23 AM
?
Extracting data from JSON file shows /Date(1435837792000+0000)/
How can I format the date to appear as Oct 29, 2010 9:10:23 AM
?
In Javascript, the Date prototype does not have a function like format(). However, there are several methods that can be used:
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
getHours() // Returns the hour
getMinutes() // Returns the minute
getSeconds() // Returns the second
Instead of a format function, you can create your own formatting function using the following code snippet:
function formatDate(dt) {
var monthNames = ["January", "February", "March", ...];
var h = dt.getHours(), am;
if (h > 12) {
am = 'pm';
h = h - 12;
} else {
am = 'am';
}
return monthNames[dt.getMonth()].substring(0, 3) + ' ' +
dt.getDate() + ', ' + dt.getFullYear() + ' ' +
h + ':' + dt.getMinutes() + ':' + dt.getSeconds() + ' ' +
am;
}
console.log(formatDate(new Date(1435837792000+0000)));
If you require more advanced date parsing and formatting capabilities, consider exploring the Momentjs library. Using Moment.js, you can easily achieve formatted dates with just one line of code:
moment(new Date(1435837792000+0000)).format("MMM D, YYYY hh:mm:ss A")
Utilize JavaScript to convert the data into a Date object and then perform date functions on it.
<html>
<head>
<script>
function jsonDatetoJSDate(){
var dateFromServer = "/Date(1435837792000+0000)/";
//JavaScript conversion
var parsedDate = new Date(parseInt(dateFromServer.substr(6)));
//obtaining Date Object
var updatedDate = new Date(parsedDate);
alert(updatedDate);
}
</script>
</head>
<body onload="javascript:jsonDatetoJSDate()">
Perform Date Functions using JavaScript
</body>
</html>
When it comes to the JSON data you receive, it may look something like this based on your comments:
var obj = {
"PublishDate": "\/Date(1435757849000+0000)\/"
}
If you are unable to change the value due to being surrounded by Date() and slashes, you can try the following steps:
First, escape the slashes around Date
.
obj.PublishDate.replace(/\//g, "");
Then, evaluate the remaining expression.
eval(obj.PublishDate.replace(/\//g, ""))
This should give you the actual date: Wed Jul 08 2015 11:48
To retrieve this value from your JSON data, follow these steps:
Firstly, assign it to a scope variable within your controller file (yourCtrl.js).
json = { name: 'stackoverflow',
date: 1435837792000+0000
};
$scope.today = new Date(json.date); //This will convert the date value from the JSON to a more readable format like `2015-07-02T11:49:52.000Z`
In your HTML file (today.html), use the following code snippet to display the date in your desired format:
{{ today | date:'medium' }}
The angular filter provided above will help you display the date as 'Oct 29, 2010 9:10:23 AM'.
If you need to apply additional formatting, you can do so by updating the code in this way:
$scope.today = Date(1435837792000+0000);
$scope.today = new Date($scope.today);
Next, utilize the angular filters for further customization:
{{ today | date:'MMM d, y hh:mm:ss' }}
or {{ today | date:'medium' }}
based on your specific requirements.
Start by extracting the timestamp from JSON and storing it in a Date
variable using the following method:
var json = { "PublishDate": "\/Date(1435757849000+0000)\/" };
var timestamp = parseInt(json.PublishDate.match(/\d+/)[0],10);
var date = new Date(timestamp);
Next, you can combine .toDateString()
and .toLocaleTimeString()
, which may not be completely reliable but will provide localized results:
date = date.toDateString() + ' ' + date.toLocaleTimeString('en');
alert( date === 'Wed Jul 01 2015 3:37:29 PM' );
Alternatively, you can use .toGMTString()
to get a result like Thu, 02 Jul 2015 11:49:52 GMT
(following RFC 1123).
Attempting to integrate ngtemplate-loader in a project using AngularJs 2 and Webpack 2 is proving challenging. While this setup has been successful in Angular 1.x projects with Webpack 1.x, it encounters an error when running in the browser: Uncaught Type ...
To perform database queries, I require some context information. The context functions are not accessible on the client side, so I have been passing this context as args whenever I call a server component. However, I am exploring more efficient ways to h ...
Currently, I am testing out a code snippet that allows images to flip through in a canvas element. I'm curious if it's possible to delay the image flipping effect until the viewer scrolls down to a specific section of the page where the canvas i ...
Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this. You can find my code on jsFiddle <div ng-controller="csrClrt"> <div ng:repeat="(key, item) in items track by $index"> ...
I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...
Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...
I'm attempting to retrieve data from the server through a get request using the following URL: url = /api/projects/:projectId/scenarios What is the best way to accomplish this using $http.get in AngularJS?. ...
In my application, I am utilizing the "angular-file-upload" library to save a file. Here is the code snippet that I am using: $scope.submitForm = function(valid, commit, file) { file.upload = Upload.upload({ url: '/tmp', data ...
In the process of developing an application using Marionette/Backbone, I have successfully implemented file uploads over an AJAX call. Now, I am looking for a way to provide users with feedback on when they can select the uploaded file and proceed with mod ...
I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...
I am looking for a way to dynamically change the background color based on a review rating using Vue.js. Ideally, I would like to achieve this with the following code: <div class="review" :style="reviewColor(hotel.average)"> In my methods section, ...
Is there a way to halve the yellow line or remove it from above the red box, while keeping it below? Can this be achieved using just HTML and CSS, or is JavaScript necessary? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 1 ...
I have recently organized our codebase's React components into a separate dependency to make them reusable across different projects. To improve readability, all components now utilize Webpack aliases: import TestComponent from 'components/TestCo ...
Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...
Currently, I am working with mozilla client-sessions in conjunction with express/node. My goal is to pass my session.user to the react-router within a standard * request. Despite my efforts and attempts, I keep encountering an issue where it becomes unde ...
I want to add multiple checkboxes using this method: $(".btn-sample").on("click", function() { $(".container").append( '<input class="check-sample" type="checkbox" value="'+check_value+'"/>' ); }); The issue I' ...
I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...
I have a project in mind for a simple website, akin to a stock tracker. One of the key features I'm trying to implement is using ajax to get results without having to reload the entire page. Although I am able to retrieve the HTML with the desired dat ...
I've been attempting to pass arguments from a function to the MongoDB collection find method. Here's what I have so far: async find() { try { return await db.collection('users').find.apply(null, arguments); } catch(err) { c ...
How can I smoothly transition a color as it ages using a dynamic time scale? I want to calculate the age based on the difference in time rather than triggering an animation after an event. I aim for a seamless gradient transition between two colors over a ...