What is the best way to change the date and time format using AngularJS or JavaScript?

let currentDate = "2015-12-16";
// Change format to "16 Dec 2015"
let currentTime = "17:04:43";
// Change format to "5:04pm"

Looking for a way to convert date and time formats using AngularJS or JavaScript?

Answer №1

Here is a simple example for formatting dates:

const date = "2015-12-16";
const dateObj = new Date(date);

To format the date in your controller/server/directive, use the $filter like this:

$filter("date")(dateObj, "MMM dd yyyy") == "16 Dec 2015"

If you prefer to handle this in your HTML file, bind it to the $scope:

$scope.dateObj = dateObj;

And then in your HTML file:

{{dateObj | date: 'MMM dd yyyy'}}

Answer №2

AngularJs provides a handy feature for filtering values before sending them to the view (UI).

{{ article.publish_date | date:'long' }}

This will ensure that the date is displayed correctly in the user interface.

Answer №3

var monthsArr = ["jan","feb","march","april","may","june","july","aug","sep","oct","nov","dec"];

var dateToday = new Date();

var currentMonth = monthsArr[dateToday.getMonth()];
var currentDate   = dateToday.getDate();

var currentYear  = dateToday.getFullYear();


console.log(currentDate +"-" + currentMonth + "-" + currentYear);


var currentHour = dateToday.getHours();
var currentMinutes = dateToday.getMinutes();

var timePeriod = "AM";

if(parseInt(currentHour)  > 12 ){
  currentHour = currentHour % 12 ;
  timePeriod = "PM"; 
}

console.log(currentHour + ":" + currentMinutes + " " + timePeriod);

Answer №4

Utilize this snippet:

let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

let currentDate = new Date();
let currentMonthIndex = currentDate.getMonth() + 1;
let minutes = currentDate.getMinutes() > 9 ? currentDate.getMinutes() : "0" + currentDate.getMinutes();
let hours = currentDate.getHours();
let period = "AM";

if (currentDate.getHours() == 12) {
    period = "PM";
}

if (currentDate.getHours() > 12) {
    hours = currentDate.getHours() % 12;
    period = "PM";
}

let currentTime = hours + ":" + minutes + period;
/* capturing time*/
let fullDate = currentDate.getDate() + " " + months[currentMonthIndex - 1] + " " + currentDate.getFullYear()

Answer №5

<script>
  angular.module('app', [])
    .controller('testCtrl', ['$scope', function($scope){
      var months =  ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
      var d = "2015-12-16";
      var date = new Date(d);
      var day   = date.getDate();
      var year  = date.getFullYear();


      console.log(day +"-" + months[date.getMonth()] + "-" + year);
    }])
</script>

Check out the code on Plunker here

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

Save all the text file lines into an array while getting rid of any instances of

Looking for a way to replicate the functionality of this python code using javascript and Jquery: config_array = open("config.txt").read().splitlines() This snippet reads the "config.txt" file, splits each line into an array element, and removes the &apo ...

What is the best way to show the current date and time in an Angular template while ensuring it stays up to

I'm looking to showcase the current date and time in my angular template, and have it automatically refresh when the time changes. The desired application LOOKS as follows: This snippet is from my .html template: <div class="top-right pull-right ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

Creating immersive 3D sound experiences using Web Audio and Three.js

I have a panorama player with 3D sounds that I am trying to integrate into Three.js by following this tutorial: http://www.html5rocks.com/en/tutorials/webaudio/positional_audio/ The camera remains fixed, while the 3D sounds are positioned across the scene ...

Preventing pop-up windows from appearing when triggered by a mouse click event

I am looking for a solution to trigger a popup window when a user right-clicks on a specific area. Here is the current code I am using: $("#popup").bind('mousedown', function(e) { var w; if(e.which==3) { w=window.open('link& ...

An error with code -4058 occurred when I tried to execute the command npm run start-rewired

When I start my React application using npm with the command npm run start-rewired, I encountered an error that looks like this: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="265654494c434552661608170816">[email p ...

Is it possible to pass component props to mapGetters in VueX?

Currently, I am in the process of creating a universal input Vue component. My main goal right now is to fetch the initial value from the store before focusing on manipulating the data within the input. Here's what I have so far: This seems to be wor ...

Retrieve the child scope of ng-repeat beyond the ng-repeat iteration and establish a two-way data binding

With my ng-repeat, I am attempting to include ng-model inside each repeated li, followed by two-way data binding outside of the ng-repeat. You can see the example in this jsbin: http://jsbin.com/yutinifivi/edit?html,js,output I have searched extensively f ...

error encountered when working with date arrays in JavaScript

I find myself perplexed by this particular issue. Although the following code snippet appears to function correctly, it exhibits some peculiar behavior. var tmpcurdte = eval(dataSource[i].startDate); tmpcurdte.setDate(tmpcurdte.getDate() + 1); while (tm ...

Text from the GET request is not being displayed in the textbox, although it is appearing in the div when using Jquery and Ajax

Currently, I have a webpage that features a text box which can be updated in real-time as the user types and is immediately saved to the database. Here is the code for my textarea: <textarea id="text"></textarea> My objective: If a user ope ...

How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to a ...

What could be causing my hamburger icon to malfunction?

https://codepen.io/anon/pen/QNqgMo Curious why the top line of the animation isn't moving. Any code wizards out there who can spot the mistake? Appreciate it! #hamburger-icon.active .line-1 { transform: translateY(25px) translateX(0) rotate(45deg); ...

Saving div data to a database using Ajax techniques

I have a project where I need to store div content in a database. The content looks like this: <span>name:</span><input type="text" id="inputid" value="John"><br /> To fetch this content successfully, I used innerHTML method and s ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

The height appears differently on Mozilla compared to the Chrome browser

I currently have three sections on my website: "Header" with a height of 100px. "Content Area" with a height of 462px. "Footer" with a height of 100px. The strange issue I am facing is that in Chrome, the scroll bar is invisible (which is ideal), but in ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Implementing reCAPTCHA in Spring MVC with Ajax

I've been attempting to implement Google reCAPTCHA service with Spring MVC, but I keep encountering this error in the console: http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=edede…nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrn ...

The AJAX post request contains no data (an empty string in the database)

I am facing an issue with my AJAX code. $(document).ready(function() { var activeTD; $(".td_test").click(function() { $("#bModal").modal('show'); activeTD = this; return false; }); $("#ajaxtest").submit( ...