How can I say "Today" and Yesterday" with Moment? [duplicate] - javascript

I'd like the moment().fromNow() functionality, but when the date is close it is too precise - ex. I don't want it to show 'in 3 hours' but 'today' - so basically with a 'daily' precision.
I tried using the moment().calendar() function, it doesn't format if the date difference is more than 1 day

You can also do this to get the date for today and tomorrow and yesterday
let today = moment();
let tomorrow = moment().add(1,'days');
let yesterday = moment().add(-1, 'days');

I use a combination of add() and endOf() with moment
//...
const today = moment().endOf('day')
const tomorrow = moment().add(1, 'day').endOf('day')
if (date < today) return 'today'
if (date < tomorrow) return 'tomorrow'
return 'later'
//...
[EDIT 2022-01-04] I suggest you to use now dayjs which has the very same API as moment and is lightweight ;)

You can customize the way that both the .fromNow and the .calendar methods display dates using moment.updateLocale. The following code will change the way that .calendar displays as per the question:
moment.updateLocale('en', {
calendar : {
lastDay : '[Yesterday]',
sameDay : '[Today]',
nextDay : '[Tomorrow]',
lastWeek : '[Last] dddd',
nextWeek : '[Next] dddd',
sameElse : 'L'
}
});
Based on the question, it seems like the .calendar method would be more appropriate -- .fromNow wants to have a past/present prefix/suffix, but if you'd like to find out more you can read the documentation at http://momentjs.com/docs/#/customization/relative-time/.
To use this in only one place instead of overwriting the locales, pass a string of your choice as the first argument when you define the moment.updateLocale and then invoke the calendar method using that locale (eg. moment.updateLocale('yesterday-today').calendar( /* moment() or whatever */ ))
EDIT: Moment ^2.12.0 now has the updateLocale method. updateLocale and locale appear to be functionally the same, and locale isn't yet deprecated, but updated the answer to use the newer method.

Requirements:
When the date is further away, use the standard moment().fromNow() functionality.
When the date is closer, show "today", "yesterday", "tomorrow", etc.
Solution:
// call this function, passing-in your date
function dateToFromNowDaily( myDate ) {
// get from-now for this date
var fromNow = moment( myDate ).fromNow();
// ensure the date is displayed with today and yesterday
return moment( myDate ).calendar( null, {
// when the date is closer, specify custom values
lastWeek: '[Last] dddd',
lastDay: '[Yesterday]',
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
// when the date is further away, use from-now functionality
sameElse: function () {
return "[" + fromNow + "]";
}
});
}
NB: From version 2.14.0, the formats argument to the calendar function can be a callback, see http://momentjs.com/docs/#/displaying/calendar-time/.

You can use this:
const today = moment();
const tomorrow = moment().add(1, 'days');
const yesterday = moment().subtract(1, 'days');

Here is how I do that using moment:
let today = moment().format('DD MMMM YYYY');
let tomorrow = moment().add(1, 'days').format('DD MMMM YYYY').toString();
let yesterday = moment().subtract(1, 'days').startOf('day').format('DD MMMM YYYY').toString();

I have similar solution, but allows to use locales:
let date = moment(someDate);
if (moment().diff(date, 'days') >= 2) {
return date.fromNow(); // '2 days ago' etc.
}
return date.calendar().split(' ')[0]; // 'Yesterday', 'Today', 'Tomorrow'

From 2.10.5 moment supports specifying calendar output formats per invocation
For a more detailed documentation check Moment - Calendar.
**Moment 2.10.5**
moment().calendar(null, {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
});
From 2.14.0 calendar can also take a callback to return values.
**Moment 2.14.0**
moment().calendar(null, {
sameDay: function (now) {
if (this.isBefore(now)) {
return '[Will Happen Today]';
} else {
return '[Happened Today]';
}
/* ... */
}
});

In Moment.js, the from() method has the daily precision you're looking for:
var today = new Date();
var tomorrow = new Date();
var yesterday = new Date();
tomorrow.setDate(today.getDate()+1);
yesterday.setDate(today.getDate()-1);
moment(today).from(moment(yesterday)); // "in a day"
moment(today).from(moment(tomorrow)); // "a day ago"
moment(yesterday).from(moment(tomorrow)); // "2 days ago"
moment(tomorrow).from(moment(yesterday)); // "in 2 days"

So this is what I ended up doing
var dateText = moment(someDate).from(new Date());
var startOfToday = moment().startOf('day');
var startOfDate = moment(someDate).startOf('day');
var daysDiff = startOfDate.diff(startOfToday, 'days');
var days = {
'0': 'today',
'-1': 'yesterday',
'1': 'tomorrow'
};
if (Math.abs(daysDiff) <= 1) {
dateText = days[daysDiff];
}

You can use .add() and .subtract() method to get yesterday and tomorrow date. Then use format method to get only date .format("D/M/Y"), D stand for Day, M for Month, Y for Year. Check in Moment Docs
let currentMilli = Date.now()
let today = Moment(currentMilli).format("D/M/Y");
let tomorrow = Moment(currentMilli).add(1, 'days').format("D/M/Y");
let yesterday = Moment(currentMilli).subtract(1, 'days').format("D/M/Y");
Result will be:
Current Milli - 1576693800000
today - 19/12/2019
tomorrow - 18/12/2019
yesterday - 18/12/2019

const date = moment(YOUR_DATE)
return (moment().diff(date, 'days') >= 2) ? date.fromNow() : date.calendar().split(' ')[0]

Add Past and future date in Date time picker in react-native
import DateTimePickerModal from "react-native-modal-datetime-picker";
import moment from 'moment';
let addFutureDay = new Date();
addFutureDay = moment(addFutureDay).add(2, 'day').format('MM/DD/YYYY');
const FutureMonthAdd = moment(addFutureDay, 'MM/DD/YYYY').toDate();
let addPastDate = new Date();
addPastDate = moment(addPastDate).add(-2, 'day').format('MM/DD/YYYY');
const PastMonthAdd = moment(addPastDate, 'MM/DD/YYYY').toDate();
return (
<View>
<Text> DatePickerDemo </Text>
<Button title="Show Date Picker" onPress={showDatePicker} />
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
minimumDate={PastMonthAdd}
maximumDate={FutureMonthAdd}
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
</View>
)
const formatedDate= moment(date).format("DD-MM-YYYY hh:mm:ss a")
const formatedDate2= moment(date).format("DD-MM-YYYY hh:mm A") // DD-MM-YYYY hh:mm a

Related

Moment JS from yyyy-mm-ddthh:mm:ss to MM-DD-YY mm:ss [duplicate]

I want to parse the following string with moment.js 2014-02-27T10:00:00 and output
day month year (14 march 2014)
I have been reading the docs but without success
http://momentjs.com/docs/#/parsing/now/
I always seem to find myself landing here only to realize that the title and question are not quite aligned.
If you want a moment date from a string:
const myMomentObject = moment(str, 'YYYY-MM-DD')
From moment documentation:
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.
If you instead want a javascript Date object from a string:
const myDate = moment(str, 'YYYY-MM-DD').toDate();
You need to use the .format() function.
MM - Month number
MMM - Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
FIDDLE
No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
http://es5.github.io/#x15.9.1.15
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
How to change any string date to object date (also with moment.js):
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
with moment.js:
startDate = moment(sDate);
endDate = moment(eDate);
Maybe try the Intl polyfill for IE8 or the olyfill service ?
or
https://github.com/andyearnshaw/Intl.js/

js/date : How to compare a French string date like "Vendredi 22 Mai à 22h" with current Date()

I'm trying to compare a French date in string format like Vendredi 22 Mai à 22h (literally `Friday 22 May at 10pm`` with the current date in javascript with node.js :
const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'); // or maybe with new Date.now()
const dateToCompare = "Vendredi 22 Mai à 22h"
if (dateNow <= dateToCompare) {
// Code here
}
Thanks for help !
You'll want to find a way to parse the French date, browsers don't have great consistency there. Once it's been parsed, you can check which date is more recent by converting to its "primitive value"
const currentYear = Date.now().getFullYear(); // since this isn't in your date string.
if (Date.now() <= new Date(currentYear, 5 , 22, 22).valueOf()) {
// code
}
Also see:
Date object docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Intl docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
Moment docs (a popular dates library): https://momentjs.com/
I made somethink like this if it could help someone else (definitely not the best code given my JS skills) :
const dateFormat = require('dateformat');
const monthsArr = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];
const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');
const currentYear = dateFormat(new Date(), 'yyyy');
// Split each word
let eventDate = textDescription.split(' ');
// Organize the array to save only the necessary values : day in number, month in number and hours:minutes
eventDate = [
eventDate[3],
monthsArr.indexOf(eventDate[4]),
eventDate[6]
];
// Split hours:minutes
// Modify hours number in date array
// Push minutes number to the date array
const eventHourMin = eventDate[2].split('h');
eventDate[2] = eventHourMin[0];
eventDate.push(eventHourMin[1]);
// Full date converted as yyyy-mm-dd HH:MM:ss
const formattedEventDate = dateFormat(new Date(currentYear, eventDate[1], eventDate[0], eventDate[2], eventDate[3], '00'), 'yyyy-mm-dd HH:MM:ss');
// If event date is not expired
if (dateNow < formattedEventDate) {
// code here...
}

Working with TimeStamps and Moment.js

I have a script that updates my database every day at 9:30am. I’m using Ember.js for my application and I need to write a function that checks if a timestamp is past 9:30am or not. The feature should always be showing data, so if it is before 9:30am it should show the previous day’s data and if it's after then it should show the current day's data. So essentially the function would return a correct timestamp depending on what time of day it is. I’ve tried this using moment.js but cannot figure it out. Any help would be great.
payload.forEach(function(value) {
// console.log("value: ", value );
var nineThirty = ' 09:30:00';
// Create date from input value
var inputDate = moment( value.updated_at ).format('MM/DD/YYYY');
var date = moment(inputDate + nineThirty);
console.log("input Date: ", date );
// yesterday
var yesterdayDate = moment().subtract(1, 'days');
var YD = moment( yesterdayDate ).format('MM/DD/YYYY');
var yesterday = moment(YD + nineThirty );
console.log("here: ", yesterday );
// Get today's date
var todaysDate = moment().format('MM/DD/YYYY');
var today_date = moment(todaysDate + nineThirty);
//... than something
});
use isBefore
this will check if now if 9:30 is before the current time
if true date = today's date else the date is yesterdays date
If(moment().set({hour: 9, minute: 30}).isBefore(moment())){
date = moment().format('MM/DD/YYYY');
}
else{
date= moment().subtract(1, 'days').format('MM/DD/YYYY');
}

How to get today,yesterday,or day name in javascript

I want to send message to chat user and then I store my message with date in parse format to my database.
So when I have to get chat history I have to show time like this:
if date is today show time (3pm etc)
if date is one day previous show yesterday
if day is within the same week show day name (i.e. Sunday etc)
all others show exact date
I have tried this:
var now = moment(new Date()); //todays date
var end = moment("2015-12-1"); // another date
var differn = now.diff(end, 'days');
How can I do this in JavaScript? I have tried to use momentjs.
One way to do is the following:
function getMyText(date){
if( !moment.isMoment(date) ){
date = moment(date); // ok for js date, milliseconds or string in ISO format
}
if( date.isSame(moment(), 'day') ){
return date.format('hh:mm a');
} else if( date.isSame(moment().subtract(1, 'd'), 'day') ){
return 'Yesterday';
} else if( date.isSame(moment(), 'week') ){
return date.format('dddd');
} else {
return date.format('DD/MM/YYYY');
}
}
var input = [
moment(), // now
moment().subtract(22, 'h'), // 22 hours ago
moment().subtract(3, 'd'), // 3 days ago
moment().subtract(6, 'd'), // 6 days ago
moment().subtract(15, 'd') // 15 days ago
];
for(var i=0; i<input.length; i++){
console.log( getMyText(input[i]) );
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
It uses moment isSame, format and subtract
since you're already using moment.js, you can leverage the calendar time functionality
var formats = {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
}
var date = new Date()
var output = moment().calendar(date, formats);
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
take a look at the documentation for more examples

Parse string to date with moment.js

I want to parse the following string with moment.js 2014-02-27T10:00:00 and output
day month year (14 march 2014)
I have been reading the docs but without success
http://momentjs.com/docs/#/parsing/now/
I always seem to find myself landing here only to realize that the title and question are not quite aligned.
If you want a moment date from a string:
const myMomentObject = moment(str, 'YYYY-MM-DD')
From moment documentation:
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.
If you instead want a javascript Date object from a string:
const myDate = moment(str, 'YYYY-MM-DD').toDate();
You need to use the .format() function.
MM - Month number
MMM - Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
FIDDLE
No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
http://es5.github.io/#x15.9.1.15
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
How to change any string date to object date (also with moment.js):
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
with moment.js:
startDate = moment(sDate);
endDate = moment(eDate);
Maybe try the Intl polyfill for IE8 or the olyfill service ?
or
https://github.com/andyearnshaw/Intl.js/

Categories

Resources