Formatting Date in Angular - javascript

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>

Related

Changing the format of date after picking from datepicker after SAPUI5

I have a datepicker from which I want to extract the date and display in a label. Currently the date is getting displayed in the format MM/DD/YYYY but I want it in the format MMM dd, yyyy (Nov 17, 2017). Below is the code :
screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
date.setText(screenDate);
XML :
<HBox alignItems="Center" renderType="Bare">
<Label text="Date of Screening" width="50%"/>
<DatePicker class="sapUiLargeMarginBegin" width="50%" id="screeningDate"/>
</HBox>
In addition to Naveen's answer here's the solution with your existing code:
screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
// Make date object out of screenDate
var dateObject = new Date(screenDate);
// SAPUI5 date formatter
var dateFormat = sap.ui.core.format.DateFormat.getDateInstance({pattern : "MMM dd,YYYY" });
// Format the date
var dateFormatted = dateFormat.format(dateObject);
date.setText(dateFormatted);
FYI, By getting view controls and updating the property in it is not good. It will be good if you have a model.
Solution for your problem is below,
<Label text="{
path: '/date',
type: 'sap.ui.model.type.Date',
formatOptions: {
style: 'medium',
pattern: 'MMM dd, yyyy'
}}"/>
<DatePicker dateValue="{/date}"/>
And in the controller I have a JSONModel as below,
onInit : function() {
this.model = new JSONModel({
date : new Date(0)
});
this.getView().setModel(this.model);
}

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>

Display 'Today' instead of date

I am using angular and moment.js to display dates in my app. If the user chooses a date other than today I want the format to be '12:00 PM Sat 21st Nov' which I have working when the user clicks a day from my calendar with amDateFormat
the following:
$scope.setDate = function(day){
var myDate = day.date;
$scope.date = moment($scope.date).set(
{
'year': myDate.year(),
'month': myDate.month(),
'date': myDate.date()
}).toDate();
}
<div> {{ date | amDateFormat:'h:mm A ddd Do MMM'}}</div>
If the date chosen is today how do I display the date to be '12:00 PM Today' instead?
I am not familiar with angular. However you can use moment calendar for today date.
From the doc you can tweak the calendar like this:
moment.locale('en', {
calendar : {
sameDay : 'LT [Today]'
}
});
And then call moment().calendar();
Here is a snippet with an alternative way of doing it assuming you are using a version that is at least 2.10.5:
var divTime = $('#time');
var time = moment().calendar(null, {
sameDay: 'LT [Today]'
});
divTime.text(time);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<div id="time">

Date formatting AngularJS to display only the day and month

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.

Categories