Why the following code produces strange output (looks like moment().valueOf() returns 0)
Since 7 days ago : {{(moment().valueOf() - 7*24*60*60*1000) | date:'yyyy-MM-dd' }}
returns
Since 7 days ago : 1969-12-25
You can do it with moment API :
moment().subtract('days', 7).format("YYYY-MM-DD")
Working jsfiddle : http://jsfiddle.net/D9UCF/1/
This is because:
moment#valueOf simply outputs the number of milliseconds since the
Unix Epoch, just like Date#valueOf.
[http://momentjs.com/docs/]
One way to achieve what you want is as follows:
Since 7 days ago: <span ng-bind="sevenDaysAgo"></span>
$scope.sevenDaysAgo = moment(new Date(new Date().setDate(new Date().getDate() - 7))).format('YYYY-MM-DD');
Related
I am using moment.js and getting this error:
Deprecation warning: value provided is not in a recognized RFC2822 or
ISO format. moment construction falls back to js Date(), which is not
reliable across all browsers and versions. Non RFC2822/ISO date
formats are discouraged and will be removed in an upcoming major
release. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: [0] _isAMomentObject: true, _isUTC: false, _useU
In my react component I have:
const sortTasks = (first, second) => moment(first.endDate).diff(second.endDate);
The first.enddate=‘20 dec 2018’
How can I avoid this warning in the console?
One alternative is to inform moment.js about the date format used, by providing a second parameter to the moment function.
The format of "20 dec 2018" is DD MMM YYYY".
If you have both dates in the same format, you should write
const sortTasks = (first, second) =>
moment(first.endDate, "DD MMM YYYY").diff(moment(second.endDate, "DD MMM YYYY"));
Note that the other date is also explicitly transformed to a moment, since it is expressed in a non-standard format.
You can check the details in the moment.js documentation about parsing.
If you want to find out the difference expressed in days, or in e.g. years / months / days, you can use moment.duration. Check the moment.js documentation about this feature.
E.g. to obtain the number of years, months and days between two dates, say date1 and date2, we could proceed as follows (assuming date1 is before date2):
const theDuration = moment.duration(date2, date1);
const yearsElapsed = theDuration.years();
const monthsElapsed = theDuration.months();
const daysElapsed = theDuration.days();
Hope it helps - Carlos
I am trying to implement a date-sorting method for a news list that works across browsers. However, the one method I have tried that works well, only works in Chrome:
origArt.sort(function(a, b) {
var dateA = new Date(a.date), dateB = new Date(b.date);
return dateB - dateA;
});
I also tried this code, suggested in other sorting questions as a possible solution:
origArt.sort(function(a,b){
return (b.date > a.date) ? 1 : (b.date < a.date) ? -1 : 0;
});
But, because the dates in my JSON vary from year; month & year; and month, year and day; the news list sorts in reverse
alphabetical order, not reverse chronological order.
They are strings such as: "2018.", "April 8, 2015.", and "September 2015."
Your problem is that those aren't valid date strings. From some quick testing, Chrome appears to be doing a bit of guesswork as to what you mean, but the other browsers aren't.
Chrome:
new Date("2018.")
// Mon Jan 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)
Firefox:
new Date("2018.")
// Invalid Date
And since Invalid Date > Invalid Date is always false, it isn't sorting anything. It's not just a matter of removing the period either, since "September 2015" also works in Chrome but fails in Firefox.
Ideally, you should fix your JSON or whatever code it's being generated from to use parseable date strings. If that's not an option, you'll probably have to write a custom parsing function that handles all the possible formats you might get, or see if a library like Moment.js can handle it for you.
I have an application where I need to show the date in UI like DD-MM-YYYY hh:mm:ss and again this date to timestamp.
What I have tried:
$scope.dateForUI = moment().format("DD-MM-YYYY hh:mm:ss");
Here I am getting the expected result. But I need timestamp of $scope.dateForUI as well. So I have tried
$scope.dateInTimestamp = moment().unix($scope.get_date_line);
But the console output shows the 1970 date in $scope.dateInTimestamp
My question is how I format my current date and assign it to a variable and again how to get the timestamp for this particular time.
Another thing is it possible to store the time of any timezone in to my $scope.dateForUI variable using moment.js? I need to show the IST time in every browser location.
Very new to moment.js, any help would be appreciated. Thanks in advance.
Try this:
$scope.dateInTimeStamp = moment().unix();
You can use moment-timezone to get values in fixed timezone. For example:
moment.tz("Asia/Kolkata")
Use moment.unix(Number) to get moment object from seconds since the Unix Epoch
Moreover you can use valueOf() to get milliseconds since the Unix Epoch from moment object and .unix() to get seconds.
Here a snippet to show how moment-timezone works and how you can use unix():
// basic angular mock
var $scope = {};
// Current time in India (moment object)
var momNow = moment.tz("Asia/Kolkata");
// Current time in India formatted (string)
$scope.dateForUI = momNow.format("DD-MM-YYYY HH:mm:ss");
// Current time in India as seconds from 1970 (number)
$scope.dateInTimestamp = momNow.unix();
console.log($scope.dateForUI);
console.log($scope.dateInTimestamp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>
So I'm trying to use directive amTimeAgo of momment JS in Angular, like this:
<span class="work-duration" ng-bind="item.startedAt | amTimeAgo: item.finishedAt: 'years' "></span>
I'm usting angular-moment (https://github.com/urish/angular-moment)
well, I want to show an date like, from: 02/09/2013 - to: 02/09/2015 - (2 years) or in different cases, 1 year and 3 months
Okay, in some cases the directive makes crazy calc,
some dates like this:
01/05/2012 - 30/09/2012 results in (3 years) why? Someone have any experiencie with this directive?
I tried to use the amFrom, but appears that this directive is not available in angularMoment,
in pure momment.JS:
var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b) // "a day ago"
Probably, this "from" method should works better than amTimeAgo.
Obs: in console, I got a lot of warnings about the finishedAt value:
angular-moment: Ignoring unsupported value for preprocess: 2015-10-01T03:00:00.000+0000
To avoid label of duplicate here's a brief summary of all what i did.
After spending hours of googling to calculate the difference between two dates I came across here and here where, i was convinced to use NodaTime to get difference in terms of years,months and days.My application needs accuracy to calculate pension.I used datetimepicker to get the date value from form and then i use Date.cs from here to extract the date in dd/mm/year and then insert it into database.To subtract the two dates using Period.Between(date1, date2, PeriodUnits.Years).Years how should i pass datetimepicker to it?
Here's what Jon Skeet said: "you can use LocalDateTime.FromDateTime and then use the Date property to get a LocalDate".
How should i get a complete rid of time while inserting in database as well as finding the difference while using datetimepicker instead of Datetime.
Update:
//Date of appointment
var d_app = LocalDateTime.FromDateTime(dateTimePicker1.Value).Date;
//Date of retirement
var d_ret = LocalDateTime.FromDateTime(dateTimePicker2.Value).Date;
var years=Period.Between(d_app,d_ret,PeriodUnits.Years).Years;
var months = Period.Between(d_app, d_ret, PeriodUnits.Months).Months;
var days = Period.Between(d_app, d_ret, PeriodUnits.Days).Days;
MessageBox.Show(years.ToString()+" years"+months.ToString()+"months "+days.ToString()+"days");
Giving the code datetimepicker1.value as 2/21/1990 (d_app) and datetimepicker2.value as 3/09/2015(d_ret) it returned 25 yrs 300months 9147
days.
What am i doing wrong?
You're performing three separate computations here. You only need one:
var appointment = LocalDateTime.FromDateTime(dateTimePicker1.Value).Date;
var retirement = LocalDateTime.FromDateTime(dateTimePicker2.Value).Date;
var difference = Period.Between(appointment, retirement);
MessageBox.Show(string.Format("{0} years {1} months {2} days",
difference.Years, difference.Months, difference.Days));