Date formatting AngularJS to display only the day and month - javascript

I am completed newbie to Angular. So I have date value for created_at. which is
2008-04-25 00:00:00
I want to get only the day similarly month in English. I have tried the following to make sample to get Year alone. But the filter not seems to be working. What am I doing wrong?
<h2>Recent Study</h2>
<ul ng-repeat="x in names">
<li>
<div class="date">
<span class="day">{{ x.created_at | date : 'yyyy' }}</span>
<span class="month">Jul</span>
</div>
<p>{{ x.study_description }}</p>
</li>
</ul>

You need to convert the date to seconds, and use a custome filter:
app.filter('toSec', function($filter) {
return function(input) {
var result = new Date(input).getTime();
return result || '';
};
});
and use it in your HTML like this:
{{ '2008-04-25 00:00:00' | toSec | date:'EEEE'}}
result:
Friday
Angular gives you the option to create a Custome Filter
Here's a working example that achieves what you need using a custome filter.

created_at's formatting isn't compatible.
Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.
Cited from https://docs.angularjs.org/api/ng/filter/date
for example "2008-04-25T00:00:00" would work.

I hope your getting the input as time stamp ,in your code just change the filter to get the only day
<h2>Recent Study</h2>
<ul ng-repeat="x in names">
<li>
<div class="date">
<!-- getting only day -->
<span class="day">{{ x.created_at | date:'dd '}}</span>
<!-- getting month name and day only -->
<span class="month">{{ x.created_at | date:'MMM-dd '}}</span>
</div>
<p>{{ x.study_description }}</p>
</li>
</ul>
here date:'dd ' gives Day in month, padded (01-31) and
date:'MMM-dd ' gives Month in year (Jan-Dec) and above day in month.

I have found the answer. The problem is simple. We should convert the mysql date time to javascript date time then only you can format it in javascript.
so my format is:2008-04-25 00:00:00
app.filter('format', function () {
return function (item) {
var t = item.split(/[- :]/);
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
var time=d.getTime();
return time;
};
});
I have converted the mysql to javascript and then to millisecond then applied my filter its working.This may be not efficient. Its working in great manner. Hope this helps someone.
so my html:
<li ng-repeat="x in names">
<div class="date">
<span class="day">{{ x.created_at | format | date:'d'}}</span>
<span class="month">{{ x.created_at | format | date:'MMM'}}</span>
</div>
<p>{{ x.study_description | makeUppercase}}</p>
</li>
Its working fine. #Nishanth answer is giving me undefined. I have upvoted it since its seems working fine for some people. The date format support vary on browser tools too.

Related

timezones with moment Js

I have this code block where I have scheduledTime and timezone received from API for example
scheduledTime: 1603890000000
timezone: "EDT"
and I would like to display this in the timezone of the device of the user i.e CST. What's the best way around it?
<p className="content mb-0 mt-2" style={{color:"#868686"}}>
{moment(new Date(workout.scheduledTime)).format("hh:mm A")}{" to "}
{moment(new Date(workout.scheduledTime)).add(workout.duration, "minutes").format("hh:mm A")}{" "}
</p>
Use toLocale()* function families to display the date in the correct locale
const theDate = new Date( Date.parse('10/28/2020 4:52:48 PM UTC'));
console.log(theDate.toLocaleString())
console.log(theDate.toLocaleTimeString());
console.log(theDate.toLocaleDateString());

angularjs format date not working

I am trying to 2015-04-17 12:44:38.0 to dd/MM/yyyy format in angularjs
<td ng-bind="item.MON_FE_DUEDATE | date:'dd-MM-yyyy'"></td>
But still showing 2015-04-17 12:44:38.0 only.Please suggested to me where is my mistake?
Because you are trying to format it on a string.
Please see working fiddle.
https://jsfiddle.net/p7gz0opm/
Converted string to Date.
function MyCtrl($scope) {
$scope.date = new Date('2015-04-17 12:44:38.0 ');
}
Template:
<div ng-app ng-controller="MyCtrl">
{{date | date:'dd-MM-yyyy'}}<br />
{{date}}
</div>
Edit :
In your case you will have to pass through a function.
Please see another fiddle.
https://jsfiddle.net/qjs1uj37/
$scope.parth=function(str){
return new Date(str);
}

Date in input is different from the one saved in database

I am using a type date to get the date but the date that i picked and the date that is saved inside the database is different. The date that is saved will always be the one day before the date that i picked. For example, in my input the date is 8 august but in the database it's saved as 7 august. How do i go abt fixing this and also how do i display the date without the T16:00:00.000Z.
dairy.html
<div>
<label> Date: </label>
<input type="date" ng-model="diary.date">
</div>
data.html
<table style="width:90%" align="center" class="t3" ng-controller="RetrieveDiaryController">
  <tr>
    <th style="width:40%">Date</th>
    <th style="width:30%">Type</th>
    <th style="width:30%">Level</th>
  </tr>
<tr ng-repeat="d in diaries | orderBy:'date':true">
<td>{{d.date}}</td>
<td>{{d.taken}}</td>
<td>{{d.level}}</td>
</tr>
</table>
health.js
.
controller('TrackingController', ['$scope', 'Diary', '$state', function($scope, Diary, $state) {
$scope.diaries = [];
$scope.submitForm = function() {
Diary
.upsert({
date: $scope.diary.date,
taken: $scope.diary.taken,
level: $scope.diary.level
})
.$promise
.then(function() {
$state.go('data');
});
};
}])
.controller('RetrieveDiaryController', ['$scope', 'Diary', function ($scope, Diary) {
$scope.diaries = Diary.find();
}])
This is due to the timezone values of the date and some difference in it between the machine you input the date and the server the db runs on. If you want to just save the simple date string, use Date object methods like getDay() or getFullYear to create a date string and then save it to the database.
YYYY-MM-DDTHH:mm:ss.SSS is the standart ISO datetime format for UTC. If you want to get it in YYYY-MM-DD format without converting it to local time, you can do it like this.
//used for padding left with 0 on one character strings. e.g. "1" => "01"
var pad = function(str){ str = str.toString(); return "00".substring(0, 2-str.length) + str; }
var date = new Date("2016-08-02T16:00:00.000Z");
var utcdatestring = date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate());
console.log(utcdatestring); //Logs "2016-08-02"
However, I highly recommend using Moment.js, since working with dates in javascript is really cumbersome with vanilla javascript.
var date = moment.utc("2016-08-02T23:00:00.000Z"); //parse datetime string as utc date
var utcdatestring = date.format("YYYY-MM-DD"); //use .format() to get date string in any format you want
console.log(utcdatestring); // Logs "2016-08-02"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
Try the basic date Filter or angular
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="datCtrl" ng-model="test='2016-08-02T16:00:00.000Z'">
<p>Date = {{ test| date }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
$scope.today = new Date();
});
</script>
</body>
</html>

Formatting Date in Angular

Currently, my Angular code displays the date like this:
03/10/2016
<span class="num">{{appointment.calendarSlot}}</span>
I want to display the date like this:
Friday, March 25
how can I do that?
UPDATE: The appointment.calendarSlot is a string and not Javascript Date
You can use the following date filter:
<span class="num">{{ appointment.calendarSlot | date:'EEEE, MMMM d' }}</span>
Try this:
https://docs.angularjs.org/api/ng/filter/date
This line is for you:
'fullDate': equivalent to 'EEEE, MMMM d, y' for en_US locale (e.g. Friday, September 3, 2010)
scope.date = new Date() // controller
{{date | date:'EEEE, MMMM dd'}} // view
You could try this
<div ng-app='app' ng-controller="ctrl">
<span class="num" ng-bind="appointment.calendarSlot | date:'EEEE, MMMM d'"></span>
</div>
JS
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.appointment = {};
$scope.appointment.calendarSlot = new Date('03/10/2016');
});
Working JSFiddle here http://jsfiddle.net/WfuAh/150/
To make this the most flexible, I would add a custom filter to your app that converts the string to a date and then you can use the built in Angular date formatting filter.
.filter("asDate", function() {
return function(input) {
return Date.parse(input);
}
})
Then your markup becomes:
<span class="num">{{ appointment.calendarSlot | asDate | date:'EEEE, MMMM d' }}</span>

How to group by a date with a timestamp? (AngularJS)

I have the following code:
<div ng-repeat="(key, value) in history | groupBy:'date'">
<div>{{key}}</div>
<div ng-repeat="item in value">
{{item}}
</div>
</div>
I want to show my history in this format:
2015-10-10
item 1
item 2
item 3
2015-10-11
item 4
item 5
2015-10-12
item 6
item 7
This code works correctly, but the date property is a timestamp. Each item differs by hours and seconds. It's important that the items are grouped by day without the time.
According to this answer made by the author of angular-filter I found a nice solution using momentjs:
html
<div ng-repeat="(key, value) in history | map: toDay | groupBy:'date'">
<div>{{key}}</div>
<div ng-repeat="item in value">
{{item}}
</div>
</div>
controller
$scope.toDay = toDay;
function toDay( history ) {
history.day = moment( history.date ).format( "L" );
return history;
}
Assuming you have a valid javascript Date object without using momentjs your function would be alike:
function toDay( history ) {
history.date = history.date.toLocaleDateString();
return history;
};
I got stuck on this for hours as a backend developer but I realised you can use time ago it's the same as moment but it can quit ckly format your timestamp.
E.g groupBy | datesubmitted : timeago then it will group by hours, days and etc

Categories