Use date-fns to format day as UTC - javascript

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?

Related

How to create Google calendar link date in Javascript 2022?

In 2022 the create Google calendar event link looks like this:
https://calendar.google.com/calendar/u/0/r/eventedit?sf=true&output=xml&text=sometext&location=somelocation&details=somedetails&dates=20220418T013000Z/20220416T020000Z
How do you formate such date in Javascript?
const formatDate = (date) => {
???
};
const myDate = new Date();
const myFormattedDate = formatDate(myDate);
console.log(myFormattedDate)
expecting output:
20220418T013000Z
Any nice looking and easy solution (rather than getHours(),getMinutes(),etc.)?
JS Dates have an inbuilt .toISOString() method which gets the right format, then just remove special characters:
let date = new Date();
let isoDate = date.toISOString()
let formattedDate = isoDate.replace(/[^\w\s]/gi, '');
console.log(formattedDate)

date comparison moment js

I want to compare two dates and my date format is DD-MM-YYYY but I don't know why my output returns false when I compare my dates.
example 1
const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1) < moment(date2); // return false, should return true
example 2
const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1).isBefore(date2); // return false, should return true
There are two issues there:
You're expecting moment to guess the format of your dates, but it can't do that reliably. Always provide a format string if your string isn't in a RFC2822 or ISO-8601 format. moment itself warns you about doing that in the dev version of the library:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/
< cannot be used to meaningfully compare objects. If you want to know if a date is before another date, use the isBefore method.
For example:
const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Convert given timestamp to influxdb timestamp

My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())

From date to date validation using javascript

I want to validate from and to date. my date format is d/m/Y H:i
Here is my code:
var startDate = new Date($('#fromdate').val());
var endDate = new Date($('#todate').val());
if (endDate.getTime() <= startDate.getTime()) {
return [false,"To Date cannot be less than From Date"];
}else{
return [true,""];
}
result showing 'Invalid Date'.
Here the date format is different. How to change the date format before passing to Date function?.
You can parse the date string on your own or you can use an external library, like dayjs or momentjs
A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):
function getDateFromCustomFormat(dateString) {
const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/
const parts = dateString.match(dateFormatPattern)
console.log(parts)
const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
new Date(validFormatString)
}

Get timestamp from date string without timezone and timezone name apart

I have a dateTime string in this (bad, I know) format coming from an external API:
const startDate = '2/13/2020 15:00';
and the timezone name:
const timezoneName = 'America/New_York';
Which means that the dateTime is 2/13/2020 15:00 in New York.
Any idea for an elegant way to get timestamp (or JavaScript date object)?
I don't mind using moment.js or/and moment-timezone if it helps.
Moment and Moment-Timezone are for legacy code.
For new applications, the Moment team recommends Luxon.
const startDate = '2/13/2020 15:00';
const timezoneName = 'America/New_York';
const dateTime = luxon.DateTime.fromFormat(startDate, 'M/d/yyyy HH:mm',
{ zone: timezoneName });
const utcDateTime = dateTime.toUTC();
const s = utcDateTime.toISO();
console.log(s); //=> "2020-02-13T20:00:00.000Z"
Using moment-timezone should work:
const moment = require('moment-timezone');
const t = moment.tz("2/13/2020 15:00", "MM/DD/YYYY HH:mm","America/New_York");
console.log(t.toISOString()); // Prints '2020-02-13T20:00:00.000Z'

Categories

Resources