Converting lengthy timestamp for year extraction in TypeScript

I am facing a challenge with extracting the year from a date of birth value stored as a long in an object retrieved from the backend. I am using Angular 4 (TypeScript) for the frontend and I would like to convert this long value into a Date object in order to calculate the age. However, I am unsure about how to accomplish this parsing in TypeScript. Can anyone provide guidance on where to find relevant information?

Perhaps something similar to:

a: Number;
let a = new Date(762861060).getFullYear();

Thank you in advance for your assistance.

Answer №1

Just a small adjustment, if you're okay with whole years:

let birthDate = new Date(762861060);
let currentDate = new Date();  
let ageInYears = currentDate.getFullYear() - birthDate.getFullYear();

Answer №2

Here is a simple code snippet for calculating age:

var birthDate = new Date(762861060);
var todayDate = new Date();    
var milliDay = 1000 * 60 * 60 * 24; // represents a day in milliseconds;

var ageInDays = (todayDate - birthDate) / milliDay;   
var ageInYears =  Math.floor(ageInDays / 365 );

console.log(ageInYears)

To explore more answers related to age calculation, you can visit this and this questions...

Answer №3

If you're looking to calculate age in days and years, Moment.js is a great tool:

import * as moment from 'moment';

var difference = moment.duration((moment(762861060)).diff(moment()));
var ageInDays = difference.days();
var ageInYears = difference.years();

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

Aligning the tooltip element vertically

I've created a unique flexbox calendar layout with CSS tooltips that appear on hover. One challenge I'm facing is vertically aligning these tooltips with the corresponding calendar dates effectively. Although I prefer to achieve this alignment u ...

Guide to successfully downloading an xlsx file in angular through express

I am creating an xlsx file based on user input within the express framework. The data is sent via a post request and I intend to send back the file content using res.download(...). However, when I do this, the data field in my ajax response ends up contai ...

When attempting to replace the outdated Angular 2 router with the new Router, I encountered an error

I have the main app component and I want to add subroutes under the admin component like /admin/users, /admin/subscribers @Component({ selector: 'my-app', template: `<router-outlet></router-outlet>` directives: [ROUTER_DI ...

Guide to Re-rendering a component inside the +layout.svelte

Can you provide guidance on how to update a component in +layout.svelte whenever the userType changes? I would like to toggle between a login and logout state in my navbar, where the state is dependent on currentUserType. I have a store for currentUserTyp ...

Discovering the Best Way to Display Node.js API Errors in an Angular Application

When encountering an error in my Node.js application, I handle it like so: app.get('/api/login', (req, res, next) => { //... return res.status(400).send({ isSuccess: false, errors: ["error 1", "error 2"] }) }) Now ...

Using a generic type as a value in an abstract class <T, K extends keyof T> allows for flexible and dynamic data manipulation

Currently, I am in the process of transferring some logic to an abstract class. Let's look at the abstract generic class with specific constraints: abstract class AbstractVersion< TModel extends object, TProperty extends keyof TModel, T ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

What is the best way to send two Array objects through http requests in AngularJS?

Is there a way to receive two parameters as an array in an HTTP action, like List `abc` and List `xyz`, and then use a model class? public class ItemAndChecque { public List<SaleItem> saleitem { get; set; } public List<itemChecqe> item ...

Breaking up and processing a given string in JavaScript: Splitting and token

When it comes to dealing with this specific JavaScript requirement, the challenge lies in working with a string such as: “ [ condition12 (BRAND) IN 'Beats by Dr. Dre & D\’Silva of type Band’ of type 'IDENTIFIER_STRING’ ] ...

Selenium unfortunately does not fully function with JavascriptExecutor

When I attempt to input text using JavascriptExecutor, the code snippet below is what I use: private void inputWorkDescription(WebDriver driver, int rawNumber) throws IOException, GeneralSecurityException { if (!getWorkDescriptionFromSheets(rawNum ...

Is it better to have a single object with all required modules in NodeJS, or follow the "standard" paths in the code?

Being a fan of creating global namespaces in javascript, I often use this approach in my app development. For instance, if my application is named Xyz, I typically create an object called XYZ to organize properties and nested objects like so: XYZ.Resource ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...

Tips on updating the datepicker format to be dd/mm/yyyy in ngbdatepicker

I am currently using ng-bootstrap for a datepicker and need to change the date format from yyyy/mm/dd to dd/mm/yyyy. I have tried to make this adjustment but haven't had success. If anyone has suggestions on how to accomplish this, please help. Here ...

Determine the central x and y coordinates of elements depending on the specified screen dimensions

Is it possible to determine the center position of an element at a specific screen size using jQuery? I am looking to calculate the center position of an element based on provided height and width dimensions. For instance, if I provide the screen size (1 ...

Solving the Challenge of URL Issue in Ajax Call to MVC Controller

I have searched extensively for a solution to my jQuery/MVC problem, but haven't found one that works. Here is the JavaScript code I am using: $.ajax({ type: "POST", url: '@Url.Action("Search","Controller")& ...

What is the process for generating an Electronic Program Guide for television?

Welcome to the forum! I'm a front-end developer at a company for 6 months now, currently working on a TV app. It's my first experience in this field and I'm facing some challenges, particularly with creating an epg for the app. Unfortunately ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...