How to get today,yesterday,or day name in javascript - 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

Related

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

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

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/

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');
}

Date formatting and comparing dates

I want to check to see if a date is before today. If it is then I want to display the date but not the time, if it is today then I want to display the time and not the date. The date I am checking is in the dd-mm-yyy hh:mm format and so they do not compare.
Please see what I have below so far:
var created = '25-05-2012 02:15';
var now = new Date();
if (created < now) {
created_format = [ format the date to be 25-05-2012 ]
} else {
created_format = [ format the date to be 02:15 ]
}
I have tried using now.dateFormat() and now.format() after seeing these in other examples but I get "is not a function" error messages.
Start by getting the parts of your date string:
var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date();
// Test if it's today
if (bits[0] == now.getDate() &&
bits[1] == (now.getMonth() + 1) &&
bits[2] == now.getFullYear() ) {
// date is today, show time
} else {
// date isn't today, show date
}
Of course there are other ways, but I think the above is the easiest. e.g.
var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
// otherDate is before today
} else {
// otherDate is not before today
}
Similarly, once you've converted the string to a date you can use getFullYear, getMonth, getDate to compare with each other, but that's essentially the same as the first approach.
You can use getTime method and get timestamp. Then you can compare it with current date timestamp.

Date Parsing and Validation in JavaScript

How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.
If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”.
if (txtDate && txtDate.value == "")
{
txtDate.focus();
alert("Please enter a date in the 'Date' field.")
return false;
}
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)
Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:
//today (right now !-) can be constructed by an empty constructor
var today = new Date();
var olddate = new Date(2008,9,2);
var diff = today.getTime() - olddate.getTime();
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds
alert(diffInDays);
This will return a decimal number, so probably you'll want to look at the integer-value:
alert(Math.floor(diffInDays));
To get the date difference in days in plain JavaScript, you can do it like this:
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
However if you want to get more control in your date manipulation I suggest you to use a date library, I like DateJS, it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:
// What date is next thrusday?
Date.today().next().thursday();
//or
Date.parse('next thursday');
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
You can use this to check for valid date
function IsDate(testValue) {
var returnValue = false;
var testDate;
try {
testDate = new Date(testValue);
if (!isNaN(testDate)) {
returnValue = true;
}
else {
returnValue = false;
}
}
catch (e) {
returnValue = false;
}
return returnValue;
}
And this is how you can manipulate JS dates. You basically create a date object of now (getDate), add 31 days and compare it to the date entered
function IsMoreThan31Days(dateToTest) {
if(IsDate(futureDate)) {
var futureDateObj = new Date();
var enteredDateObj = new Date(dateToTest);
futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.
//adds hours and minutes to dateToTest so that the test for 31 days is more accurate.
enteredDateObj.setHours(futureDateObj.getHours());
enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);
if(enteredDateObj >= futureDateObj) {
return true;
}
else {
return false;
}
}
}
Hello and good day for everyone
You can try Refular Expressions to parse and validate a date format
here is an URL yoy can watch some samples and how to use
http://www.javascriptkit.com/jsref/regexp.shtml
A very very simple pattern would be: \d{2}/\d{2}/\d{4}
for MM/dd/yyyy or dd/MM/yyyy
With no more....
bye bye

Categories

Resources