Working with TimeStamps and Moment.js - javascript

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

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/

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

Timestamp Date & Time Format - Apps Script - Format Date and Time

I can't get the time-stamp format in a spreadsheet cell to also include the time. Currently, it only produces the date. What do I need to change to get the time-stamp to show both date and time?
Like this:
3/17/2015 10:57:45
function onEdit(event)
{
var ss = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(r.getColumn() == 8){ //To check if update cell in Column, 1 means first column.
if(r.getValue() == "Resolved"){ //To check the value is equal to Resolved
ss.getRange('L'+r.getRow()).setValue(new Date()); //Set column B1 value to current date.
date = Utilities.formatDate(time, "GMT", "HH:mm:ss");
}else{
ss.getRange('L'+r.getRow()).setValue('');
}
}
You need to use:
var formattedDate = Utilities.formatDate(time, "GMT", "MM-dd-yyyy HH:mm:ss");
There is an example in the documentation:
Google Documentation - formatDate
In you code, get the time zone of the script like this:
var timeZone = Session.getScriptTimeZone();
date = Utilities.formatDate(new Date(), timeZone, "MM-dd-yyyy | HH:mm:ss");

Date selection for week-to-date

I have a comboBox DateType with options Today, Yesterday, Week-to-date and Manual Entry.
I also have 2 textboxes - one for Start Date and one for End Date.
By default, the DateType will be set to Today's date.
For eg.: Let's say, current date is 01/11/2011 (Tues)
When DateType : Today
Start Date = 01/11/2011
End Date = 01/11/2011
When DateType : Week-to-date (Note: Each week will be `Sun to Sat`)
Start Date = 01/09/2012 (Sun)
End Date = 01/11/2012 (Current Date)
Few Variables:
var startDate = new Date(document.getElementsByName('Start Date').value);
var endDate = new Date(document.getElementsByName('End Date').value);
I am new to javascript, so could anyone help me frame a function that can modify the Start Date and End Date based on the DateType selected(as above).
I need the condition only for Week-to-date
The rest would be similar,I guess, so I can frame the remaining conditions.
Thanks in advance!
In response to the onchange event of the select control you can set a date range something like:
function setDateRange()
{
var periodSelection = dateseln.period.options[dateseln.period.selectedIndex].value;
var start;
switch (periodSelection)
{
case "Today":
start = new Date();
break;
case "WeekToDate":
start = new Date();
start.setDate(start.getDate() - start.getDay());
break;
}
dateseln.startDate.value = start;
dateseln.endDate.value = new Date();
}

Categories

Resources