moment.js is unable to extract the time information from a timestamp

I'm having trouble converting a timestamp using moment.js from a json data set. When I try to use

moment.format('MMMM Do YYYY, H:mm:ss')
, the output is showing something like May 25th 2361, 0:00:00 for the timestamp 12351223423. This seems to happen for all timestamps I've tested so far. Does anyone know why it doesn't display the correct time and how can I fix this?

Here's an excerpt from my Angular controller:

$scope.timeFormat = function(timestamp) {
    var dt = moment.unix(timestamp);

    if(++recheckDate % 25 == 0)
    {
        // predefined variables
        today = moment().startOf('day');
        yesterday = moment().subtract(1, 'days');
    }

    if(dt.startOf('day').isSame(today))
        return dt.format('[Today], H:mm:ss');
    if(dt.startOf('day').isSame(yesterday))
        return dt.format('[Yesterday], H:mm:ss');

    return dt.format('MMMM Do YYYY, H:mm:ss');
};

Below is the HTML code snippet (trimmed down, assuming the controller and app setup are functional for other fields):

<div ng-repeat="item in data">
    <span class="time">{{ timeFormat(item.time) }}</span>
</div>

UPDATE: You can view an online demo here. The error still persists. The source code can be found on GitHub.

Answer №1

It took me much longer than expected to figure this out...

dt.startOf('day') actually changes dt, it doesn't create a copy.

moment().startOf(String);
This method alters the original moment by setting it to the beginning of a unit of time.

Therefore, you should use clone():

if(dt.clone().startOf('day').isSame(today))
    return dt.format('[Today], H:mm:ss');
if(dt.clone().startOf('day').isSame(yesterday))
    return dt.format('[Yesterday], H:mm:ss');

Alternatively, try a different approach that doesn't change the original moment.

When troubleshooting similar issues, consider hardcoding all values and utilizing console.log extensively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Live Update Google Sheet Data to JSON Without Reloading Web Page

This particular function is executing smoothly. My main concern lies in updating a DOM element without reloading the webpage, if any alterations are made to the data on a Google sheet I am utilizing a JSON file from Google sheets: https://spreadsheets.g ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...

Troubleshooting the 'App Already Bootstrapped with this Element' Error in AngularJS

When I try to load my AngularJS app, I encounter the following error: Uncaught Error: [ng:btstrpd] App Already Bootstrapped with this Element '<html lang="en" ng-app="app" class="ng-scope">' I have only placed ng-app once in the html elem ...

Ways to disseminate arguments when dealing with an array of arrays in JavaScript

Struggling to pass an array as arguments into the join method on path in node, but hitting a roadblock: var path = require("path"); var paths = [__dirname]; var userInput = ["app", "js"]; paths.push(userInput); var target = path.join.apply(null, paths); ...

What is the most straightforward AngularJs 'Hello World' example you would use when introducing AngularJs to a newcomer?

Can someone provide a beginner-friendly 'Hello World' example in AngularJS? I'm trying to learn and so far have come up with this: <!DOCTYPE html> <html> <head> </head> <body> <div data-ng-app=""> ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

What's the reason behind beforeunload not triggering?

I've gone through numerous similar posts, but I'm struggling to figure out what's not quite right with this code snippet: $(window).on("beforeunload", function () { debugger handleBeforeUnload(); return false; }); function handl ...

Is there a way to call a Vue function from an onclick event in JavaScript?

Creating a vue component and trying to call a function defined in Vue methods using the onClick attribute when modifying innerHTML is resulting in an error message stating "showModal is not defined". Here is the showModal function where I'm simply try ...

Creating textures for a blender model and animating it with JavaScript using Three.js

After successfully animating a model in Blender using bone animation and texturing it with UV mapping, I exported the model with UV and animation checked using the three.js export add-on in Blender. However, I am struggling to load the texture for the anim ...

What is the mechanism behind the jQuery ready function that enables its first parameter to transform into a jQuery object?

While browsing today, I came across this interesting code snippet: jQuery(document).ready(function($$){ console.log($$); }); It seems that $$ is recognized as the jQuery object itself. Typically, to achieve this, we would need to pass the jQuery varia ...

Tips for manually updating the $scope in AngularJS

Once a user is updated in AngularJS, I prefer to update the $scope.user with the new data rather than making a new API request to fetch all users. I have come across $apply, but I am still unsure about how to properly use it. app.controller('UserCtrl ...

Find similarities and differences between two CSV files

Dealing with 2 large files, both exceeding 1 million rows: The first file contains only an md5 hash The second file contains pairs of md5 and email addresses My task is to compare these two files and if the md5 hashes match, write the corresponding emai ...

A strategy for concealing the selected button within a class of buttons with Vanilla JS HTML and CSS

I have encountered a challenging situation where I am using JavaScript to render data from a data.json file into HTML. Everything seems to be functioning correctly, as the JSON data is being successfully rendered into HTML using a loop, resulting in multip ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

When the button is clicked, dynamically fetch data from a MySQL database using PHP without the need to refresh

I have a .php page where I am displaying a table from my MySQL database using PHP based on a cookie value. On this same page, I have implemented a feature that allows me to change the cookie data without having to reload the entire page by simply clicking ...

Tips on updating an HTML page following the receipt of a CURL request by a PHP script

I am currently developing a unique login system with customized requirements. The HTML form will submit data to a PHP script using AJAX, which will then forward the information to another PHP script for processing through CURL. After some time has passed ...

Ensuring the positioning of input fields and buttons are in perfect alignment

I've been struggling to align two buttons next to an input field, but every time I try, I end up messing everything up. I managed to align an input field with a single button, but adding a second button is proving to be quite difficult. Here is ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Consistently scaling the Embla carousel slides for a seamless presentation experience

In my current project, I am utilizing Embla Carousels and aiming to incorporate a smooth slide scaling effect as users scroll through. The idea is for slides to enlarge the closer they get to the left edge of the carousel container, then decrease in size r ...