I have the following code in my RN application.
getFormattedDate = (date) => {
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
return { date: formattedDate };
}
When I run this on the emulator, the formatted date is displayed properly. But when I run this on device, it says, invalid date. What am I doing wrong here?
From your comments, I assume that the date parameter is a string. If you want to create a new moment from a string, you have to pass the date format. The newly created moment can then be formatted with .format to get a string again.
Change:
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
To:
const formattedDate = moment(date,"MMM, DD YYYY").format("MMMM, DD YYYY");
Here you can find more details about the string format.
npm install date-fns --save
import { format } from 'date-fns'
format(new Date(), 'MMMM, DD YYYY')
Check this document
Moment is 150x slower than new Date . Please try it like this if you want to use this code working.
getFormattedDate = async (date) => {
const formattedDate = await moment(new Date(date)).format('MMMM,DD YYYY');
return { date: formattedDate };
}
you can read it here for more details
https://github.com/moment/moment/issues/731
I would suggest avoid using moment because of the performance.
Use new Date () and then fetch the day , month and year and change into suitable format by joining the strings as you want. Use only Date library.
Related
I have the following date format 2022-07-20 and I would like to parse into the following format 2022-07-20T00:00:00.000Z
I'm using the following code
const main = () => {
const day = '2022-07-20'
const date = new Date()
const result = parse(day.toString(), 'yyyy-MM-dd', date)
console.log(result.toISOString())
}
And getting the following output 2022-07-19T21:00:00.000Z. I assume this happening because my timezone is UTC+3.
How do I get it formatted as 2022-07-20T00:00:00.000Z?
I have been trying to convert this time into EST "date": "2020-04-27T14:44:42Z". I am using angular and can get it into this format myFormat: 'MMM-DD-YYYY h:mm A' but can't seem to adjust the time to reflect est. Any help would be greatly appreciated.
Using momentjs
moment timezone makes is easy and convenient to convert+format. Command for npm install moment-timezone (this solution supports DST neutral TZ string 'America/New_York' instead of EST/EDT)
npm install --save moment moment-timezone
Code
import * as moment from 'moment-timezone';
// ...
// ...
const dateFormattedInEST = moment("2020-04-27T14:44:42Z").tz('America/New_York').format('MMM-DD-YYYY h:mm A');
Output: Apr-27-2020 10:44 AM
Moment gives lot of formatting options. Documentation https://momentjs.com/docs/#/displaying/format/
Using Angular pipes
Can be done using angular pipes as well (as pointed out by JSON Derulo).
Note: the format string are different from momentjs
{{"2020-04-27T14:44:42Z" | date : 'MMM-dd-YYYY h:mm a' : 'EDT'}}
Output: Apr-27-2020 10:44 AM
If you want to get hold off string for any other manipulation
import { DatePipe } from '#angular/common';
// ...
// ...
const dataAsStr = datePipe.transform("2020-04-27T14:44:42Z", 'MMM-dd-YYYY h:mm a', 'EDT');
Output: Apr-27-2020 10:44 AM
Here is some solution that I am applying now. You can use the method toLocaleString to do this.
Example 1:
const convertUTCDateToLocalDate = date => {
const newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
const offset = date.getTimezoneOffset() / 60;
const hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
const _date = convertUTCDateToLocalDate(new Date("2020-04-27T14:44:42Z"));
_date.toLocaleString(); // "4/28/2020, 6:44:42 AM"
Example 2:
const _date = new Date("2020-04-27T14:44:42Z");
const _est_date = _date.toLocaleString("en-US", {timeZone: "America/New_York"}); // "4/27/2020, 10:44:42 AM"
Just change the locale based on the requirement from your project.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
I'm trying to add a string comma (,) between the date and time formats. Can someone kindly show how I can achieve this for the following code? I thought it might be as simple as adding a comma in between, but unfortunately this doesn't seem to be working for me.
Example:
14 JUN 21, 18:55:03
Line 1:
return handleFileType(req, res, user, dataFile, email, origin, previewSubject, finalFormatDate.format('DD MMM YY HH:mm:ss')
Line 2:
const date = moment.unix(dateToUnixTimestamp(memo.createdAt)).format('DD MMM YY HH:mm:ss');
The reason I published both these lines, is because I'm not sure if anything can vary between them.
The format method parses a format string and replaces tokens with values from the date. Non–tokens are kept as–is, so just add the comma where you want it in the format string:
format('DD MMM YY, HH:mm:ss')
let date1 = moment().format('DD MMM YY HH:mm:ss');
console.log(date1)
let date2 = moment().format('DD MMM YY, HH:mm:ss');
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
If you prefer to avoid using moment.js, it is also possible with native Date javascript class methods:
let a = new Date();
let timeStr = a.toLocaleTimeString('en-GB')
let dateStr = a.toLocaleDateString('en-GB')
let timeDateStr = dateStr + ', ' + timeStr;
console.log(timeDateStr);
I have a working instance of Vue Datepicker, which is functional to the point of picking a date and logging it on select within the console.
The problem is that it logs as Fri Oct 18 2019 15:01:00 GMT-0400 but I need to send the formatted date portion of this like 2019-10-18 only.
This is vuejs-datepicker library and I can't seem to get anything to work with this:
customFormatter(date) {
return moment(date).format('MMMM Do YYYY, h:mm:ss a');
}
What exactly am I doing wrong here?
<datepicker :value="date" #selected="CallDateFunction"></datepicker>
date(){
return {
date: '',
...
CallDateFunction(date){
console.log(date);
}
vuejs-datepicker's selected callback is called with either a date object or null.
You can use the following example code to get a string representation of the date only:
CallDateFunction(date){
if (date) {
const dateString = date.toISOString().substring(0, 10);
console.log(dateString);
} else {
console.log('null date');
}
}
You can format your date with Date.prototype.toISOString() method and set it to your data:
callDateFunction(rawDate){
if (rawDate)
this.formattedDate = rawDate.toISOString().split('T')[0]
}
See also: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
The VueDatePicker have a Props to disable TimePicker that is true by default. As :enableTimePicker="false"
Solution:
<Datepicker v-model="date" :enableTimePicker="false"></Datepicker>
Source: https://vue3datepicker.com/api/props/#enabletimepicker
You can use the javascript function
jsref_toisostring
.
Documentation
Its pretty forward:
var d = new Date();
var n = d.toISOString();
const dt = DateTime.fromISO(new Date(date))
// dt => DateTime {ts: 1516876197386, zone: LocalZone, loc: Locale, invalid: "unparsable", weekData: null, …}
return dt.toFormat('yyyy/mm/dd')
The result is: Invalid DateTime. Why is this and how to fix it?
Luxon's docs: https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toFormat
fromISO:
Create a DateTime from an ISO 8601 string
accepts ISO string, while you are passing a JavaScript Date.
You can use Date's toISOString() or luxon fromJSDate
const DateTime = luxon.DateTime;
const dt = DateTime.fromISO(new Date().toISOString());
console.log(dt.toFormat('yyyy/MM/dd'));
const dt2 = DateTime.fromJSDate(new Date());
console.log(dt2.toFormat('yyyy/MM/dd'));
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
Moreover, note that you have to use uppercase MM to print month instead of lowercase mm that stands for minutes.
You can use fromJSDate like: luxon.DateTime.fromJSDate(new Date())