How to get a start of day date in specific timezone - javascript

I am working with Date Picker component and I am trying to get selected day from date picker to be start of day (midnight) in specific timezone (e.g. Europe/London). So for example if I select 2023-01-30 I want to get something like
Mon Jan 30 2023 00:00:00 GMT (London UK)
Currently output shows my local timezone at the end GMT-0500 (Eastern Standard Time) but I would like to have London one GMT
I am using date-fns to get startOfDay
const d = '2023-01-30';
const [year, month, day] = d.split('-');
const y = startOfDay(new Date(year, month - 1, day));
console.log('🚀 ~ file: ScheduleSection.js:102 ~ convertDateToUtc ~ y', y);
Actual Output: Mon Jan 30 2023 00:00:00 GMT-0500 (Eastern Standard Time)
Expected Output: Mon Jan 30 2023 00:00:00 GMT (London UK)

Since you have tags for date-fns and date-fns-tz, you can do what you want with those libraries. The following can be run at RunKit.com:
var dateFns = require('date-fns');
var dateFnsTz = require('date-fns-tz');
let date = '2014-06-25T00:00:00';
let timeZone = 'America/Los_Angeles';
// Parse timestamp for America/Los_Angeles
let utcDate = dateFnsTz.zonedTimeToUtc(date, timeZone);
// UTC equivalent: "2014-06-25T07:00:00.000Z"
console.log(utcDate.toISOString());
// Europe/London equivalent: "2014-06-25 08:00:00 GMT+1"
console.log(dateFnsTz.formatInTimeZone(utcDate,
'Europe/London', 'yyyy-MM-dd HH:mm:ss zzz'));
As RunKit doesn't support import, require is used instead.

you can use the moment-timezone library, you can install it by running
npm install moment-timezone
in your project's root directory.
Example:
const moment = require('moment-timezone');
const d = '2023-01-30';
const date = moment.tz(d, 'Europe/London').startOf('day').format();
console.log(date);

Related

Why does my Date subtracts one day after converting from ISO to UTC

I am creating a todo app where users are selecting from-date and to-date.
The requirement is to display the dates in the format Month Year.
On Load the dates are working as expected
const fromDate = subtractOneYearFromDate(new Date()).toISOString());
const toDate = new Date().toISOString());
function subtractOneYearFromDate(date) {
const dateCopy = new Date(date); //2022-02-13T14:00:48.945Z
dateCopy.setFullYear(dateCopy.getFullYear() - 1); //2023-02-13T14:00:48.946Z
return dateCopy;
}
However, when users are trying to change dates, it looks like the dates are one day off. Suppose I am selecting Mar 2022 from the drop down. I get e[0] only correct. So I am converting this to ISO before calling my API.
What I am trying to achieve is : 2022-03-01T16:00:00.000Z
onChange={(e) => {
console.log("e[0]", e[0]) //Tue Mar 01 2022 00:00:00 GMT+0800 (Singapore Standard Time)
console.log(JSON.stringify(e[0])) //2022-02-28T16:00:00.000Z
console.log(e[0].toUTCString()); //28 Feb 2022 16:00:00 GMT
console.log(e[0].toISOString()); //2022-02-28T16:00:00.000Z
console.log(moment.utc(e[0]).local().toISOString()) //2022-02-28T16:00:00.000Z
}

Having issue calculating timeSince due to timeZone confusion

So I am a little bit confused. the server return date is in UTC ISO format, my local time is CST.
so I use toLocaleString() and then subtract the difference but I get a negative number. I rather use react native library rather than installing new libraries such as moment
export function timeSince(date) {
//date is 2022-11-07T18:36:39.543 which is UTC, not CST
date = date.toLocaleString("en-US", {
timeZone: "CST",
});
// somehow stayed 2022-11-07T18:36:39.543
date = new Date(date);
//Mon Nov 07 2022 18:36:39 GMT-0600 (Central Standard Time)
Mon Nov 07 2022 12:29:21 GMT-0600 (Central Standard Time)
'2022-11-07T18:27:38.03'
var seconds = Math.floor((new Date() - date) / 1000); // -21506
return seconds
}

What type of date strings are these in JS?

I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.
I want to convert the first format to the second.
I am doing this in a crazy way, so I am thinking there must be a better one.
var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();
console.log(iso);
console.log(time);
var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")
var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);
The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.
2021-09-17T11:50:59-04:00 is an ISO-8601 date string.
toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you'll have to use a library such as date-fns:
import { formatISO } from 'date-fns'
formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))
// prints '2021-09-17T11:50:59-04:00'

How do I parse the output of `date -u` (unix date command, UTC) using moment.js?

I literally just noticed that the unix date command does not output iso8601 or RFC2822 format dates. 🙁
I've got some input json documents with the date specified as the output of unix date -u, e.g.: Mon Oct 22 04:08:48 UTC 2018. My dates are always in UTC because they were generated with date -u. (Next time I'll be smart and just use date -u +"%Y-%m-%dT%H:%M:%SZ" to get an iso8601 date.)
I've scoured the documentation for parsing and searched the web thoroughly, but can't figure out what I'm doing wrong.
I am trying to parse these using moment.js:
const instr = 'Mon Oct 22 03:53:08 UTC 2018';
const dateFormatString = "ddd MMM DD HH:mm:ss [UTC] GGGG";
const parsedDate = moment.utc(instr, dateFormatString, true);
It's still just giving me:
moment.invalid(/* Mon Oct 22 03:53:08 UTC 2018 */)
What am I doing wrong?
Example:
https://jsfiddle.net/1c3g0r4j/
var parseString = 'Mon Oct 22 03:53:08 UTC 2018';
var formatString = 'ddd MMM DD HH:mm:ss [UTC] gggg';
var locale = 'en';
var strictParse = true;
var parsed = moment.utc(parseString, formatString, locale, strictParse);
alert(parsed.isValid()) //false
Mark Meyer above provides us with the solution, which appears to be using the locale-specific year token YYYY.
var parseString = 'Mon Oct 22 03:53:08 UTC 2018';
var formatString = 'ddd MMM DD HH:mm:ss [UTC] YYYY';
var locale = 'en';
var strictParse = true;
var parsed = moment.utc(parseString, formatString, locale, strictParse);
alert(parsed.isValid())
alert(parsed.toISOString())

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories