How to customize date-fns's formatDistance - javascript

I get the date from the backend in this format 2022-10-20T10:41:31.095
How can I customize the date?
example
today: 22:15
yesterday: yesterday 13:45
Week: Friday 14:40
a month or more: 10/27/2007
const distance = formatDistance(new Date(), new Date(wroteTime), { locale: uk });

Related

How to use a date/time "preset" from the current locale in date-fns format function?

I'm setting the default locale for date-fns this way:
import { it } from 'date-fns/locale';
import { setDefaultOptions } from 'date-fns';
setDefaultOptions ({ locale: it });
And this is working good for methods like formatDistance or formatRelative:
formatDistanceToNow(new Date(2014, 6, 2), { addSuffix: true}); // "8 anni fa"
With the "raw" format function you are forced to specify a format (second argument). Is there any way to use a "preset" for the current locale?
// The format function force you to specify the format
format(new Date(2017, 10, 6), 'dd/MM/y HH:mm'); // 06/11/2017 00:00
For example, italian language specify these presets (source code) but it's not exporting them:
const dateFormats = {
full: 'EEEE d MMMM y',
long: 'd MMMM y',
medium: 'd MMM y',
short: 'dd/MM/y',
}
const timeFormats = {
full: 'HH:mm:ss zzzz',
long: 'HH:mm:ss z',
medium: 'HH:mm:ss',
short: 'HH:mm',
}
How to pass the short date/time formats to format, instead of passing "dd/MM/y HH:mm" all the time?

Easepick - Book over a weekend without the weekend counting as days

I am trying to use the Easepick (https://easepick.com/) datepicker to create a holiday booking system.
As the working week is Monday to Friday i need to block out Saturdays and Sundays which i have managed to do.
The next issue i am working with is i need people to be able to book over the course of more than 1 week but not go above there holiday allowance so for example if someone has 5 days remaining and wants to book between Wednesday and the following tuesday they should be able to.
var maxdays = 5
const picker = new easepick.create({
element: "#datepicker",
css: [
"https://cdn.jsdelivr.net/npm/#easepick/bundle#1.1.6/dist/index.css"
],
zIndex: 10,
AmpPlugin: {
dropdown: {
months: true,
years: true,
minYear: 2021
}
},
LockPlugin: {
maxDays: maxdays,
filter(date, picked) {
return [0, 6].includes(date.getDay());
}
},
plugins: [
"AmpPlugin",
"RangePlugin",
"LockPlugin"
],
})
This is what i have so far: https://jsfiddle.net/nzLcktv4/
what can i do?

How to set second litepicker startDate based on first litepicker startDate selection

Hey my fellow Stackoverflowers, I am working with litepicker.js and ran into a snag that I am hoping one of you can help me figure out.
I have built out two separate litepickers and am successfully populating todays date on the first and tomorrows date in the second. (these are also successfully being accepted as the minDate for both)
What I have not been able to figure out is how to set the minDate for the second litepicker to one day after the selected startDate of the first litepicker.
You can see where I am at in this codepen
https://codepen.io/DigitalDesigner/pen/oNGRWzV
HTML Code:
<form>
<input id="start-date" class="form-control start-date"> /
<input id="end-date" class="form-control end-date">
</form>
Javascript:
<script>
let current = new Date();
let tomorrow = new Date(current.getTime() + 86400000); // + 1 day in ms
tomorrow.toLocaleDateString();
// Add litepicker calendar to stay dates
const startpicker = new Litepicker({
element: document.getElementById('start-date'),
singleMode: true,
allowRepick: true,
autoRefresh: true,
format: 'D MMMM YYYY',
startDate: current,
minDate: new Date(),
numberOfMonths: 1,
numberOfColumns: 1,
tooltipText: {
one: 'night',
other: 'nights'
},
tooltipNumber: (totalDays) => {
return totalDays - 1;
},
plugins: ['mobilefriendly']
});
const endpicker = new Litepicker({
element: document.getElementById('end-date'),
singleMode: true,
allowRepick: true,
autoRefresh: true,
format: 'D MMMM YYYY',
startDate: tomorrow,
minDate: current,
numberOfMonths: 1,
numberOfColumns: 1,
tooltipText: {
one: 'night',
other: 'nights'
},
tooltipNumber: (totalDays) => {
return totalDays - 1;
},
});
</script>
here is the litepicker site: https://litepicker.com/
How can I set the minDate for the second litepicker based on the first litepickers selected date?
Thanks in advance.
add this to the code
startpicker.on('selected', (date1, date2) => {
endpicker.setOptions({
minDate: startpicker.getDate(),
startDate: startpicker.getDate()
});
});

Convert TimeZone Time string correctly into Local Time

I am trying to convert a time string returned from our backend system but I am unable to get the correct local time.
Time string returned from backend: "2020-08-28T07:00:00.000Z"
Expected local time needed: Aug 28, 2020 12:00 AM
I tried:
converting it with Moment.js Failed:
moment(backendTime).format(
"MMM D,YYYY h:mm a"
)
Somehow I got "Jan 1st 20 12:00 AM", I don't understand it at all
converting it by casting to Date Failed as well:
Date("2020-08-28T07:00:00.000Z")
Ended up getting: " Mon Sep 21 2020 00:07:29 GMT-0700 (Pacific Daylight Time) "
I am running out of ideas right now, I feel it shouldn't be this difficult but just cannot get it.
The format you are getting is exactly what you have requested.
To get the output you desire using moment.js you need to use the following format:
moment(backendTime).format("MMM DD, YYYY hh:mm A");
You can test it here: https://jsfiddle.net/oz6mx3nh/
In vanilla JS you can use the DateTimeFormat to format your dates based on a timezone. All the options for DateTimeFormat are documented here.
The different options for the locale (en-US) is listed here
Here is a full list of all the time zones.
See bottom snippet for the output of each locale (in the provided list)
const date = new Date("2020-08-28T07:00:00.000Z");
const format = new Intl.DateTimeFormat(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
hour: "2-digit",
hour12: true,
minute: "2-digit",
timeZone: "America/New_York",
}
).format(date)
console.log(format);
A list of outputs from every locale:
const date = new Date("2020-08-28T07:00:00.000Z");
const locales = ["ar-SA", "bn-BD", "bn-IN", "cs-CZ", "da-DK", "de-AT", "de-CH", "de-DE", "el-GR", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-NZ", "en-US", "en-ZA", "es-AR", "es-CL", "es-CO", "es-ES", "es-MX", "es-US", "fi-FI", "fr-BE", "fr-CA", "fr-CH", "fr-FR", "he-IL", "hi-IN", "hu-HU", "id-ID", "it-CH", "it-IT", "jp-JP", "ko-KR", "nl-BE", "nl-NL", "no-NO", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sk-SK", "sv-SE", "ta-IN", "ta-LK", "th-TH", "tr-TR", "zh-CN", "zh-HK", "zh-TW"];
const formatDate = (locale, date) => new Intl.DateTimeFormat(
locale,
{
month: "short",
day: "2-digit",
year: "numeric",
hour: "2-digit",
hour12: true,
minute: "2-digit",
timeZone: "America/New_York",
}
).format(date);
// Loop over each locale
for(const locale of locales) {
const formatted = formatDate(locale, date);
console.log(`${locale}: ${formatted}`);
}
A few things:
Assuming your computer is set for Pacific time, then:
moment("2020-08-28T07:00:00.000Z").format("MMM D, YYYY h:mm a")
//=> "Aug 28, 2020 12:00 am"
That will indeed return the value you expected. You said you got "Jan 1st 20 12:00 AM", but that is not possible, as neither the values nor the format matches.
When you tried the Date object, you got the result you did because you omitted the new keyword (see this explanation). It should instead be:
new Date("2020-08-28T07:00:00.000Z")
Keep in mind that this produces a Date object. If you log that object directly, the result is implementation specific. It may vary across browsers. Instead, you should call a function such as toString or toLocaleString from it.
If this is a new project, you should probably avoid using Moment. Please read https://momentjs.com/docs/#/-project-status/

Date range picker start date & locale format not setting in angular view

Start Date & Format not setting in date range picker, please find the code below
Issue: Start date and format not bind properly in the view
In Controller
$scope.pngDatePicker = { startDate: moment().subtract(1, "days"), endDate: moment() };
$scope.pngDatePickerOpts = {
autoApply: true,
locale: { format: 'YYYY-MM-DD' },
dateLimit: {
months: 3
},
maxDate: moment()
};
In view
<input type="daterange" data-ng-required="true" date-range-picker ng-model="pngDatePicker" options="pngDatePickerOpts" id="dateRange" class="form-control date-picker">
Output:
Date range Picker Output in angularjs view

Categories