I use moment(d, "YYYYMMDD").fromNow(); to get diff between date now and some date, but I would like to get without string "a few days ago".
Instead, I would like to get "7d" (7m, 1s, etc).
How can I do this?
If you want just to get the difference between two dates instead of a relative string just use the diff function.
var date = moment("20170101", "YYYYMMDD");
var date7 = moment("20170108", "YYYYMMDD");
var mins7 = moment("20170101 00:07", "YYYYMMDD HH:mm");
var secs1 = moment("20170101 00:00:01", "YYYYMMDD HH:mm:ss");
console.log(date7.diff(date, "days") + "d"); // "7d"
console.log(mins7.diff(date, "minutes") + "m"); // "7m"
console.log(secs1.diff(date, "seconds") + "s"); // "1s"
Moment.diff does exactly that.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
You can specify a unit:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
var before = moment('2017.02.12 09:00','YYYY.MM.DD HH:mm');
var now = moment();
console.log(
moment(now - before)
.format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Related
I'm using moment.js diff to compare two times,but the result is incorrect
var moment = require('moment.js')
console.show()
var mydate = new Date();
myhours = mydate.getHours()
myminutes = mydate.getMinutes()
var a = moment([2007, 0, 29]);
var b = moment([2007, parseInt(myhours), parseInt(myminutes)]);
log(b.diff(a,'minutes'))
I want the result to be correct
You are trying to use the hours and minutes of myDate like month and day in the array to pass at moment constructor.
You can change b with this code:
const b = moment([2007, 0, 29, parseInt(myhours), parseInt(myminutes)]);
or using the methods of moment:
const b = moment().year(2007).startOf('minute');
.year() set the year of date, and .startOf() rounds the time to start of minute.
This can be a solution, if I understood what do you want:
const moment = require('moment.js');
const a = moment([2007, 0, 29]); // 2007-01-29 00:00:00
const b = moment().year(2007).startOf('minute'); // 2007-01-12 14:34:00
console.log(b.diff(a, 'minutes')); // -23606 -> use Math.abs(b.diff(a, 'minutes')) for the absolute value, your choice.
I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.
In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date.
I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.
If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “
function Put_Options_Expiry_Alert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Long equity (sell puts)");
//var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet
var status = sheet.getRange("F:F").getValues();
var expiry_date = sheet.getRange("M:M").getValues();
var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();
Logger.log("Length of status = " + status.length);
Logger.log("Length of expiry_date = " + expiry_date.length);
Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);
for (var i = 0; i < status.length; i++) {
if (status[i] == "Entered") { //Evaluate if this is a live Put position
//Calculate the time difference of two dates using date2. getTime() – date1. getTime();
//Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
Logger.log("expiry date is = "+expiry_date[i]);
Logger.log("today's date is = "+Date());
var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
Logger.log(days_to_expiry);
}
}
}
// Function that returns the number of days difference between DateA and DateB
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day
const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());
return Math.floor((utc2 - utc1) / milliseconds_per_day);
}
function timeDiffDays(Start, End) {
var day = 86400000;
var t1 = new Date(Start).valueOf();
var t2 = new Date(End).valueOf();
var d = t2 - t1;
return Math.floor(d / day);
}
I'm trying to this code in the Script Editor of Google Sheets to insert today's date along with a consistent piece of text, and it was working fine up until Jan 31, 2021, when it started inserting 2021-02-32, 2021-02-33, etc. instead of 2021-02-01, 2021-02-02, etc. Here's the code I'm running:
function daily() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Social Tracker");
var date = Utilities.formatDate(new Date(), "GMT", "YYYY-MM-DD");
var aValues = sh.getRange("A1:A").getValues();
var aLast = aValues.filter(String).length;
// Assuming A and B have same last row, no need for B
// If different, need to calculate separately
var bValues = sh.getRange("B1:B").getValues();
var bLast = bValues.filter(String).length;
// If A and B are the same, use setValues
sh.getRange(aLast + 1, 1, 1, 2).setValues([[date,'handle']]);
var sheet = SpreadsheetApp.getActiveSheet();
var followers = sheet.getRange(2,5,sheet.getLastRow()).getValues();
var nextRowJ = getFirstEmptyRow('J');
var following = sheet.getRange(2,6,sheet.getLastRow()).getValues();
var nextRowK = getFirstEmptyRow('K');
var engagement = sheet.getRange(2,7,sheet.getLastRow()).getValues();
var nextRowL = getFirstEmptyRow('L');
var likes = sheet.getRange(2,8,sheet.getLastRow()).getValues();
var nextRowM = getFirstEmptyRow('M');
var comments = sheet.getRange(2,9,sheet.getLastRow()).getValues();
var nextRowN = getFirstEmptyRow('N');
var posts = sheet.getRange(2,4,sheet.getLastRow()).getValues();
var nextRowO = getFirstEmptyRow('O');
// Record current balance and timestamp at end of columns B & C
sheet.getRange(nextRowO, 15, 1, 1).setValues([[posts]]);
sheet.getRange(nextRowJ, 10, 1, 1).setValues([[followers]]);
sheet.getRange(nextRowK, 11, 1, 1).setValues([[following]]);
sheet.getRange(nextRowL, 12, 1, 1).setValues([[engagement]]);
sheet.getRange(nextRowM, 13, 1, 1).setValues([[likes]]);
sheet.getRange(nextRowN, 14, 1, 1).setValues([[comments]]);
}
// From https://stackoverflow.com/a/9102463/1677912
function getFirstEmptyRow(columnLetter) {
columnLetter = columnLetter || 'A';
var rangeA1 = columnLetter + ':' + columnLetter;
var spr = SpreadsheetApp.getActiveSpreadsheet();
var column = spr.getRange(rangeA1);
var values = column.getValues(); // get all data in one call
var ct = 0;
while ( values[ct][0] != "" ) {
ct++;
}
And here's an image of the cells that are being filled in by the script. I'm assuming my issue is with the line:
sh.getRange(aLast + 1, 1, 1, 2).setValues([[date,'consistent piece of text']]);
How can I adjust this to make sure it follows the next date in A1, ie. inserts 2021-02-01 instead of 2021-02-32?
Use:
var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
Reason:
Utilities.formatDate(date, timeZone, format) follows this format guidelines
When you use "DD", you specify the Day in a year. If you want to specify the Day of the month you need to use dd
In addition, when you use "YYYY" you are referring to a Week year. If you want to get the actual year use "yyyy" instead.
If you find using Java SE Simple Date Format counterintuitive and you are using Google Apps Script V8 runtime instead of using Utilities.formatdate() you might use to Date.prototype.toLocaleDateString
Instead of "YYYY-MM-DD" use "yyyy-MM-dd"
YYYY stands for 4 digit weak year (the first/last week of the year it might return a number different of what you are expecting.
yyyy stands for 4 digit year
DD stands for day year (32 is February 1st)
MM stands for 2 digit month (02 is February)
mm stats for 2 digit minutes
I want to add time/duration in HH:mm(eg 00:10) to a Date time in format MM-DD-YYYY HH:MM
I have date and time in 2 separate objects so am trying the below
var plannedStartDate = document.getElementById("date1"); //eg 02-12-2020
var plannedStartTime = document.getElementById("plannedStart1"); //eg 09:00
var plannedStartDateTime = moment(plannedStartDate.value + " " + plannedStartTime.value);
var minutes = $("#duration1").text().split(':')[1];
var hours = $("#duration1").text().split(':')[0];
var date = plannedStartDateTime.add(hours, 'hours').add(minutes, 'minutes').format("MM-DD-YYYY HH:mm");
console.log("Final:"+date); //gives invalid date
What am I doing wrong
Check this working sandbox: https://codesandbox.io/s/compassionate-bas-fg1c2
It adds the hours and minutes to the input date and then prints in a given format
var moment = require("moment");
var input = "2020-02-12";
var hoursMinutes = "9:10";
var hours = hoursMinutes.split(":")[0];
var minutes = hoursMinutes.split(":")[1];
var momentInTime = moment(input)
.add(hours, "hours")
.add(minutes, "minutes");
var converted = moment(momentInTime).format("DD-MM-YYYY HH:mm:ss");
console.log(converted);
in flutter we can get current month using this
var now = new DateTime.now();
var formatter = new DateFormat('MM');
String month = formatter.format(now);
But how to get the last month date? Especially if current date is January (01). we can't get the right month when we use operand minus (-) , like month - 1.
You can just use
var prevMonth = new DateTime(date.year, date.month - 1, date.day);
with
var date = new DateTime(2018, 1, 13);
you get
2017-12-13
It's usually a good idea to convert to UTC and then back to local date/time before doing date calculations to avoid issues with daylight saving and time zones.
We can calculate both first day of the month and the last day of the month:
DateTime firstDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month, 1);
DateTime lastDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month + 1).subtract(Duration(days: 1));
DateTime.utc takes in integer values as parameters: int year, int month, int day and so on.
Try this package, Jiffy, it used momentjs syntax. See below
Jiffy().subtract(months: 1);
Where Jiffy() returns date now. You can also do the following, the same result
var now = DateTime.now();
Jiffy(now).subtract(months: 1);
We can use the subtract method to get past month date.
DateTime pastMonth = DateTime.now().subtract(Duration(days: 30));
Dates are pretty hard to calculate. There is an open proposal to add support for adding years and months here https://github.com/dart-lang/sdk/issues/27245.
There is a semantic problem with adding months and years in that "a
month" and "a year" isn't a specific amount of time. Years vary by one
day, months by up to three days. Adding "one month" to the 30th of
January is ambiguous. We can do it, we just have to pick some
arbitrary day between the 27th of February and the 2nd of March.
That's why we haven't added month and year to Duration - they do not
describe durations.
You can use the below code to add months in a arbitrary fashion (I presume its not completely accurate. Taken from the issue)
const _daysInMonth = const [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
bool isLeapYear(int value) =>
value % 400 == 0 || (value % 4 == 0 && value % 100 != 0);
int daysInMonth(int year, int month) {
var result = _daysInMonth[month];
if (month == 2 && isLeapYear(year)) result++;
return result;
}
DateTime addMonths(DateTime dt, int value) {
var r = value % 12;
var q = (value - r) ~/ 12;
var newYear = dt.year + q;
var newMonth = dt.month + r;
if (newMonth > 12) {
newYear++;
newMonth -= 12;
}
var newDay = min(dt.day, daysInMonth(newYear, newMonth));
if (dt.isUtc) {
return new DateTime.utc(
newYear,
newMonth,
newDay,
dt.hour,
dt.minute,
dt.second,
dt.millisecond,
dt.microsecond);
} else {
return new DateTime(
newYear,
newMonth,
newDay,
dt.hour,
dt.minute,
dt.second,
dt.millisecond,
dt.microsecond);
}
}
To get a set starting point at the start of a month, you can use DateTime along with the Jiffy package.
DateTime firstOfPreviousMonth
= DateTime.parse(
Jiffy().startOf(Units.MONTH)
.subtract(months: 1)
.format('yyyy-MM-dd'). //--> Jan 1 '2021-01-01 00:00:00.000'
);
var fifthOfMonth
= firstOfPreviousMonth.add(Duration(days: 4)); //--> Jan 5 '2021-01-05 00:00:00.000'
or
DateTime endOfPreviousMonth
= DateTime.parse(
Jiffy().endOf(Units.MONTH)
.subtract(months: 2)
.format('yyyy-MM-dd'). //--> Dec 30 '2020-12-31 00:00:00.000'
// endOf always goes to 30th
);
var previousMonth
= endOfPreviousMonth.add(Duration(days: 2)); //--> Jan 1 '2021-01-01 00:00:00.000'
DateFormat('MMMM yyyy')
.format(DateTime(DateTime.now().year, DateTime.now().month - 2)),
List<DateTime> newList = [];
DateFormat format = DateFormat("yyyy-MM-dd");
for (var i = 0; i < recents.length; i++) {
newList.add(format.parse(recents[i]['date'].toString()));
}
newList.sort(((a, b) => a.compareTo(b)));
var total = 0;
for (var i = 0; i < newList.length; i++) {
if (DateTime.now().difference(newList[i]).inDays < 30) {
print(newList[i]);
total++;
}
}
print(total);
You can use this to fetch the last 30 days.
In addition to Günter Zöchbauer Answer
var now = new DateTime.now();
String g = ('${now.year}/ ${now.month}/ ${now.day}');
print(g);