date-fns#isYesterday JavaScript Examples
The following examples show how to use
date-fns#isYesterday.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js From nyc-makers-vs-covid with GNU General Public License v3.0 | 7 votes |
export function formatDateDistance(date) {
let deliveryDate = parse(date, 'MM/dd/yyyy', new Date())
if (isToday(deliveryDate)) {
return 'Today'
} else if (isYesterday(deliveryDate)) {
return 'Yesterday'
} else {
return formatDistanceStrict(deliveryDate, startOfToday(), {
unit: 'day',
addSuffix: 'true'
})
}
}
Example #2
Source File: helpers.js From monsuivipsy with Apache License 2.0 | 6 votes |
formatRelativeDate = (date) => {
const isoDate = parseISO(date);
if (isToday(isoDate)) {
return "aujourd'hui";
} else if (isYesterday(isoDate)) {
return "hier";
} else {
return format(isoDate, "EEEE d MMMM", { locale: fr });
}
}
Example #3
Source File: helpers.js From monsuivipsy with Apache License 2.0 | 6 votes |
formatDateThread = (date) => {
const isoDate = parseISO(date);
if (isToday(isoDate)) {
return "Aujourd'hui";
} else if (isYesterday(isoDate)) {
return "Hier";
} else {
const formattedDate = format(isoDate, "EEEE d MMMM", { locale: fr });
return firstLetterUppercase(formattedDate);
}
}
Example #4
Source File: Chat.jsx From airdrop with MIT License | 6 votes |
RenderDate = ({ date }) => {
if (isToday(new Date(date))) {
return (
<div
style={{ padding: '5px 12px 6px', textAlign: 'center' }}
className={`${Styles.other} rounded-lg shadow-md text-sm`}
>
Today
</div>
);
}
if (isYesterday(new Date(date))) {
return (
<div
style={{ padding: '5px 12px 6px', textAlign: 'center' }}
className={`${Styles.other} rounded-lg shadow-md text-sm`}
>
Yesterday
</div>
);
}
return (
<div
style={{ padding: '5px 12px 6px', textAlign: 'center' }}
className={`${Styles.other} rounded-lg shadow-md text-sm`}
>
{new Date(date).toDateString()}
</div>
);
}
Example #5
Source File: ConversationTime.js From airdrop with MIT License | 6 votes |
export default function ConversationTime(date) {
// Check if it is a valid date
if (date === 'Invalid Date') return '';
if (isToday(date)) {
return format(date, 'hh:mm a');
}
if (isYesterday(date)) {
return 'Yesterday';
}
return format(date, 'dd/MM/yy');
}
Example #6
Source File: LastSeen.js From airdrop with MIT License | 6 votes |
export default function LastSeen(date) {
// Check if it is a valid date
if (date === 'Invalid Date') return '';
if (isToday(date)) {
return format(date, "'last seen at' hh:mm a");
}
if (isYesterday(date)) {
return format(date, "'last seen yesterday at' hh:mm a");
}
return format(date, "'last seen' MMM dd 'at' hh:mm a");
}
Example #7
Source File: jobs.js From remotebear with GNU Affero General Public License v3.0 | 5 votes |
export function getJobs({ query, locationId, departmentId, companyId }) {
return allJobs
.filter((job) => {
const company = allCompaniesById[job.companyId];
const disabled = job?.status === "disabled";
let satisfiesQuery = true;
if (query) {
satisfiesQuery =
searchInString(job.title, query) ||
searchInString(job.location, query) ||
searchInString(company.name, query);
}
let satisfiesLocationId = true;
if (!job.normalizedLocation.length) {
satisfiesLocationId = false;
} else if (locationId) {
satisfiesLocationId =
job.normalizedLocation.includes(locationIds.global) ||
job.normalizedLocation.includes(locationId);
}
let satisfiesDepartmentId = true;
if (departmentId) {
satisfiesDepartmentId =
departmentId === departmentIds.engineering
? job.normalizedDepartment === departmentId
: !job.normalizedDepartment;
}
let satisfiesCompanyId = true;
if (companyId) {
satisfiesCompanyId = job.companyId === companyId;
}
return (
satisfiesQuery &&
satisfiesLocationId &&
satisfiesDepartmentId &&
satisfiesCompanyId &&
!disabled
);
})
.map((job) => {
// Add a new "formattedCreatedAt" field holding a human readable date
let formattedCreatedAt;
if (isToday(job.createdAt)) {
formattedCreatedAt = "Today";
} else if (isYesterday(job.createdAt)) {
formattedCreatedAt = "Yesterday";
} else {
formattedCreatedAt = formatDistanceToNow(job.createdAt, {
addSuffix: true,
});
}
// Capitalize
formattedCreatedAt = `${formattedCreatedAt
.charAt(0)
.toUpperCase()}${formattedCreatedAt.slice(1)}`;
// Denormalize the company infos into "company" to avoid loading them
// on the client side
const iconName = companyFaviconPathsByCompanyIds[job.companyId];
const company = {
id: allCompaniesById[job.companyId].id,
name: allCompaniesById[job.companyId].name,
iconUrl: `/company-favicons/${iconName}`,
};
return { ...job, company, formattedCreatedAt };
});
}
Example #8
Source File: index.js From monsuivipsy with Apache License 2.0 | 4 votes |
Events = ({ navigation, fromDate, toDate, focusedScores }) => {
const [diaryData] = React.useContext(DiaryDataContext);
const [activeCategories, setActiveCategories] = React.useState();
const [isEmpty, setIsEmpty] = React.useState();
const chartDates = getArrayOfDatesFromTo({ fromDate, toDate });
const [symptom, setSymptom] = React.useState("ANXIETY");
const [event, setEvent] = React.useState("ALL");
const [score, setScore] = React.useState([5]);
useFocusEffect(
React.useCallback(() => {
(async () => {
const q = await buildSurveyData();
if (q) {
setActiveCategories(q.map((e) => e.id));
setSymptom(q[0].id);
}
})();
}, [])
);
// React.useEffect(() => {
// console.log("✍️ ~ symptom", symptom);
// }, [symptom]);
const memoizedCallback = React.useCallback(() => {
if (!symptom) return [];
// console.log("SYMPTOME", symptom);
if (!score || !score.length) return [];
const targetScore = score[0];
// console.log("score", score);
if (!event) return [];
// console.log("event", event);
return chartDates.map((date) => {
let infoDate = { date };
// console.log("✍️ ~ date", date);
const dayData = diaryData[date];
if (!dayData) {
// console.log("no dayData");
return {};
}
const categoryState = diaryData[date][symptom];
// console.log("✍️ ~ categoryState", categoryState);
if (!categoryState) {
// console.log("categoryState");
return {};
}
if (diaryData[date][symptom]?.value !== targetScore) {
return {};
}
// { label: "Tous les évènement", value: "ALL" },
// { label: "Contexte de la journée", value: "CONTEXT" },
// { label: "Précisions élément", value: "USER_COMMENT" },
// { label: "Traitements", value: "POSOLOGY" },
// { label: "Substances", value: "TOXIC" },
if (dayData?.CONTEXT?.userComment) infoDate = { ...infoDate, CONTEXT: dayData?.CONTEXT?.userComment };
if (categoryState?.userComment) infoDate = { ...infoDate, USER_COMMENT: categoryState?.userComment };
// console.log("✍️ ~ infoDate", infoDate);
return infoDate;
// -------
// the following code is for the retrocompatibility
// -------
// get the name and the suffix of the category
// const [categoryName, suffix] = symptom.split("_");
// let categoryStateIntensity = null;
// if (suffix && suffix === "FREQUENCE") {
// // if it's one category with the suffix 'FREQUENCE' :
// // add the intensity (default level is 3 - for the frequence 'never')
// categoryStateIntensity = diaryData[date][`${categoryName}_INTENSITY`] || { level: 3 };
// return { value: categoryState.level + categoryStateIntensity.level - 2 };
// }
// return { value: categoryState.level - 1 };
});
}, [symptom, score, event, chartDates, diaryData]);
const startSurvey = async () => {
const symptoms = await localStorage.getSymptoms();
logEvents.logFeelingStart();
if (!symptoms) {
navigation.navigate("symptoms", {
showExplanation: true,
redirect: "select-day",
});
} else {
navigation.navigate("select-day");
}
};
const renderDate = (d) => {
if (isYesterday(parseISO(d))) return "hier";
if (isToday(parseISO(d))) return "aujourd'hui";
let relativeDate = formatRelativeDate(d);
return `le ${relativeDate}`;
};
if (isEmpty) {
return (
<View style={styles.emptyContainer}>
<View style={styles.subtitleContainer}>
<Icon icon="InfoSvg" width={25} height={25} color={colors.LIGHT_BLUE} />
<Text style={styles.subtitle}>
Des <Text style={styles.bold}>Évènements</Text> apparaîtront au fur et à mesure de vos saisies
quotidiennes.
</Text>
</View>
<Button title="Commencer à saisir" onPress={startSurvey} />
</View>
);
}
return (
<>
<View style={styles.filterContainer}>
<View style={styles.filterItemContainer}>
<Text style={styles.text}>Afficher tous les évènements associés à</Text>
{/* <SelectEvent
options={activeCategories}
onChange={setEvent}
placeholder="Choisir évènement"
value={event}
/> */}
</View>
<View style={styles.filterItemContainer}>
{/* <Text>associé(s) à</Text> */}
<SelectSymptom
options={activeCategories}
onChange={setSymptom}
onOpen={logEvents.logSuiviEditSymptom}
placeholder="Sélectionner un élément"
value={symptom}
/>
</View>
<View style={styles.containerScorePickerFrise}>
<ScorePicker
focusedScores={score}
onPress={(i) => {
setScore([i]);
logEvents.logSuiviEditScoreEvents(i);
}}
/>
</View>
</View>
<ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContainer}>
{memoizedCallback()?.filter((x) => x.date)?.length === 0 && (
<Text style={styles.noDataMessage}>
Aucun évènement à afficher entre {renderDate(formatDay(fromDate))} et{" "}
{renderDate(formatDay(toDate))}.
</Text>
)}
{memoizedCallback()
?.filter((x) => x.date)
?.sort((a, b) => {
const ad = a.date.split("/").reverse().join("");
const bd = b.date.split("/").reverse().join("");
return bd.localeCompare(ad);
})
?.map((d) => {
return (
<Card
key={d.date}
event={event}
date={d.date}
context={d.CONTEXT}
userComment={d.USER_COMMENT}
/>
);
})}
</ScrollView>
</>
);
}
Example #9
Source File: daySurvey.js From monsuivipsy with Apache License 2.0 | 4 votes |
DaySurvey = ({ navigation, route }) => {
const [diaryData, setDiaryData] = useContext(DiaryDataContext);
const [questions, setQuestions] = useState([]);
const [answers, setAnswers] = useState({});
const questionToxic = {
id: "TOXIC",
label: "Avez-vous consommé des substances aujourd'hui ?",
};
const questionContext = {
id: "CONTEXT",
label: "Ajoutez une note générale sur votre journée",
};
useFocusEffect(
React.useCallback(() => {
(async () => {
const q = await buildSurveyData();
if (q) {
setQuestions(q);
}
})();
}, [])
);
useEffect(() => {
//init the survey if there is already answers
Object.keys(route?.params?.currentSurvey?.answers || {})?.forEach((key) => {
const score = getScoreWithState({
patientState: route?.params?.currentSurvey?.answers,
category: key,
});
const cleanedQuestionId = key.split("_")[0];
if (questions.find((q) => q.id === cleanedQuestionId)) {
toggleAnswer({ key: cleanedQuestionId, value: score });
handleChangeUserComment({
key: cleanedQuestionId,
userComment: route?.params?.currentSurvey?.answers[cleanedQuestionId]?.userComment,
});
}
});
if ((route?.params?.currentSurvey?.answers || {})[questionToxic.id]) {
toggleAnswer({
key: questionToxic.id,
value: route?.params?.currentSurvey?.answers[questionToxic?.id]?.value,
});
handleChangeUserComment({
key: questionToxic.id,
userComment: route?.params?.currentSurvey?.answers[questionToxic?.id]?.userComment,
});
}
if ((route?.params?.currentSurvey?.answers || {})[questionContext.id]) {
handleChangeUserComment({
key: questionContext.id,
userComment: route?.params?.currentSurvey?.answers[questionContext?.id]?.userComment,
});
}
}, [route?.params?.currentSurvey?.answers, questions, questionToxic.id, questionContext?.id]);
const toggleAnswer = async ({ key, value }) => {
setAnswers((prev) => {
return {
...prev,
[key]: { ...prev[key], value },
};
});
};
const handleChangeUserComment = ({ key, userComment }) => {
setAnswers((prev) => {
return {
...prev,
[key]: { ...prev[key], userComment },
};
});
};
const submitDay = async ({ redirectBack = false }) => {
const prevCurrentSurvey = route.params?.currentSurvey;
const currentSurvey = {
date: prevCurrentSurvey?.date,
answers: { ...prevCurrentSurvey.answers, ...answers },
};
setDiaryData(currentSurvey);
logEvents.logFeelingAdd();
logEvents.logFeelingAddComment(
Object.keys(answers).filter(
(key) => ![questionToxic.id, questionContext.id].includes(key) && answers[key].userComment
)?.length
);
logEvents.logFeelingAddContext(answers[questionContext.id]?.userComment ? 1 : 0);
logEvents.logFeelingResponseToxic(answers[questionToxic.id]?.value ? 1 : 0);
if (route.params?.redirect) {
alertNoDataYesterday({
date: prevCurrentSurvey?.date,
diaryData,
navigation,
});
return navigation.navigate("tabs");
}
if (redirectBack) {
return navigation.goBack();
}
const medicalTreatmentStorage = await localStorage.getMedicalTreatment();
if (medicalTreatmentStorage?.length === 0) {
alertNoDataYesterday({
date: prevCurrentSurvey?.date,
diaryData,
navigation,
});
return navigation.navigate("tabs");
}
navigation.navigate("drugs", {
currentSurvey,
editingSurvey: route.params?.editingSurvey,
});
};
const renderQuestion = () => {
if (isYesterday(parseISO(route.params?.currentSurvey?.date)))
return "Comment s'est passée la journée d'hier ?";
if (isToday(parseISO(route.params?.currentSurvey?.date))) return "Comment s'est passée votre journée ?";
let relativeDate = formatRelativeDate(route.params?.currentSurvey?.date);
relativeDate = `le ${relativeDate}`;
return `Comment s'est passé ${relativeDate} ?`;
};
return (
<SafeAreaView style={styles.safe}>
<BackButton onPress={() => submitDay({ redirectBack: true })} />
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "position" : "height"} style={{ flex: 1 }}>
<ScrollView
style={styles.container}
keyboardDismissMode="on-drag"
onScrollBeginDrag={Keyboard.dismiss}
>
<TouchableOpacity
onPress={() => {
navigation.navigate("symptoms");
logEvents.logSettingsSymptomsFromSurvey();
}}
>
<View style={styles.linkContainer}>
<Text style={styles.link}>Ajouter ou retirer des indicateurs de mon questionnaire</Text>
<View style={styles.linkButtonContainer}>
<ArrowUpSvg color="#fff" />
</View>
</View>
</TouchableOpacity>
<Text style={styles.question}>{renderQuestion()}</Text>
{questions.map((q, i) => (
<Question
key={i}
question={q}
onPress={toggleAnswer}
selected={answers[q.id]?.value}
explanation={q.explanation}
onChangeUserComment={handleChangeUserComment}
userComment={answers[q.id]?.userComment}
/>
))}
<InputQuestion
question={questionContext}
onPress={toggleAnswer}
selected={answers[questionContext.id]?.value}
explanation={questionContext.explanation}
onChangeUserComment={handleChangeUserComment}
userComment={answers[questionContext.id]?.userComment}
placeholder="Contexte, évènements, comportement de l’entourage..."
/>
<QuestionYesNo
question={questionToxic}
onPress={toggleAnswer}
selected={answers[questionToxic.id]?.value}
explanation={questionToxic.explanation}
isLast
onChangeUserComment={handleChangeUserComment}
userComment={answers[questionToxic.id]?.userComment}
/>
<View style={styles.divider} />
<View style={styles.buttonWrapper}>
<Button onPress={submitDay} title="Valider" />
</View>
<Text style={styles.subtitle}>
Retrouvez toutes vos notes dans l'onglet "Mon journal"
</Text>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Example #10
Source File: survey-screen.js From monsuivipsy with Apache License 2.0 | 4 votes |
SurveyScreen = ({navigation, route}) => {
const [totalQuestions, setTotalQuestions] = useState(0);
const [questions, setQuestions] = useState([]);
const [question, setQuestion] = useState();
const [answers, setAnswers] = useState();
const [explanation, setExplanation] = useState();
const [currentSurveyItem, setCurrentSurveyItem] = useState();
const [questionId, setQuestionId] = useState();
const [index, setIndex] = useState(route.params?.index);
const [availableData, setAvailableData] = useState();
const updateValues = () => {
if (!availableData || index < 0 || !availableData[index]) return;
setQuestion(availableData[index]?.question);
setAnswers(availableData[index]?.answers);
setExplanation(availableData[index]?.explanation);
setCurrentSurveyItem(index);
setQuestionId(availableData[index]?.id);
};
useEffect(() => {
(async () => {
const q = await buildSurveyData();
if (q) {
setQuestions(q);
setTotalQuestions(q.length);
}
const d = await getAvailableData();
if (d) setAvailableData(d);
})();
}, []);
useEffect(() => {
updateValues();
}, [route, availableData]);
const nextQuestion = (answer) => {
let currentSurvey = {};
if (currentSurveyItem !== 0) {
currentSurvey = {...route.params.currentSurvey};
}
if (answer) {
// if date selection
if (answer.id === 'DATE') {
currentSurvey = {
date: formatDay(beforeToday(answer.dateOffset)),
answers: {},
};
return navigation.navigate('day-survey', {
currentSurvey,
});
} else {
currentSurvey.answers[questionId] = answer;
}
}
let redirection = 'notes';
let nextIndex = -1;
if (!isLastQuestion()) {
const isNextQuestionSkipped = answer.id === 'NEVER';
// getting index of the current question in the 'questions' array
const index = questions.indexOf(currentSurveyItem);
// getting the next index of the next question
const nextQuestionIndex = index + (isNextQuestionSkipped ? 2 : 1);
// if there is a next question, navigate to it
// else go to 'notes'
if (nextQuestionIndex <= questions.length - 1) {
const nextQuestionId = questions[nextQuestionIndex];
redirection = 'question';
nextIndex = nextQuestionId;
}
}
setIndex(nextIndex);
navigation.navigate(redirection, {
currentSurvey,
backRedirect: currentSurveyItem,
index: nextIndex,
});
};
const previousQuestion = () => {
const survey = route.params?.currentSurvey;
// getting index of the current question in the 'questions' array
const index = questions.indexOf(currentSurveyItem);
if (index <= 0) {
navigation.navigate('tabs');
return;
}
// getting the router index of the previous question
let previousQuestionIndex = questions[index - 1];
const previousQuestionId = availableData[previousQuestionIndex].id;
if (!survey?.answers[previousQuestionId])
previousQuestionIndex = questions[index - 2];
setIndex(previousQuestionIndex);
navigation.navigate('question', {
...route.params,
index: previousQuestionIndex,
});
};
const isLastQuestion = () => {
return questions.indexOf(currentSurveyItem) === totalQuestions - 1;
};
if (!question || !availableData) return null;
if (questionId === 'day') {
const now = new Date(Date.now());
return (
<SafeAreaView style={styles.safe}>
<BackButton onPress={previousQuestion} />
<ScrollView style={styles.container}>
<Text style={styles.question}>{question}</Text>
{[...Array(7)].map((_, i) => {
const value = formatDay(subDays(now, i));
let label = firstLetterUppercase(formatRelativeDate(value));
return (
<TouchableOpacity
key={i}
onPress={() => nextQuestion({id: 'DATE', dateOffset: i})}>
<View style={styles.answer}>
<View style={styles.answerLabel}>
<CircledIcon color="white" icon="TodaySvg" />
<Text style={styles.label}>{label}</Text>
</View>
<ArrowUpSvg style={styles.arrowRight} color={colors.BLUE} />
</View>
</TouchableOpacity>
);
})}
<Text style={styles.subtitleTop}>Attention !</Text>
<Text style={styles.subtitle}>
Je ne peux pas remplir au-delà de 7 jours car les informations
seront alors moins fidèles
</Text>
</ScrollView>
{explanation ? <SurveyExplanation explanation={explanation} /> : null}
</SafeAreaView>
);
}
const renderQuestion = () => {
let relativeDate = formatRelativeDate(route.params?.currentSurvey?.date);
if (
!isYesterday(parseISO(route.params?.currentSurvey?.date)) &&
!isToday(parseISO(route.params?.currentSurvey?.date))
)
relativeDate = `le ${relativeDate}`;
return question.replace('{{date}}', relativeDate);
};
return (
<SafeAreaView style={styles.safe}>
<BackButton onPress={previousQuestion} />
<ScrollView style={styles.container}>
<Text style={styles.question}>{renderQuestion()}</Text>
{answers
.filter((answer) => answer.id !== 'NOTES')
.map((answer, index) => (
<TouchableOpacity key={index} onPress={() => nextQuestion(answer)}>
<View style={styles.answer}>
<View style={styles.answerLabel}>
<CircledIcon color={answer.color} icon={answer.icon} />
<Text style={styles.label}>{answer.label}</Text>
</View>
</View>
</TouchableOpacity>
))}
</ScrollView>
{explanation ? <SurveyExplanation explanation={explanation} /> : null}
</SafeAreaView>
);
}