Luxon fromFormat pattern ignore time - javascript

When I try to create Date object from string format in Luxon I get invalid date.
Hours and minutes are not passed. This gives me an Invalid date
const dateString = '28.09.2022';
DateTime.fromFormat(dateString, 'dd.LL.yyyy HH:mm').toJSDate();
// Invalid date
Using moment library it seems that if hours and minutes are not passed it defaults to 00:00:00
const dateString = '28.09.2022';
moment(date, 'DD.MM.YYYY HH:mm').toDate();
// Wed Sep 28 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time)
Is there some option to format both formats with hours and without in Luxon using one method as I was using moment in many places and it accepted 'DD.MM.YYYY HH:mm' format no matter if you pass HH:mm in string?

No, I fear that there is no native way to get moment(String, String) behaviour in Luxon. Moreover, it seems that there is no counterpart of moment(String, String[]) in Luxon.
Please note that, while "Moment's parser is very forgiving", Luxon Parsing section of the docs states that "Luxon is quite strict about the format matching the string exactly."
You can build your own custom method and implement the business logic you need, here a possible example:
const DateTime = luxon.DateTime;
const customParse = (dateString) => {
let dt = DateTime.fromFormat(dateString, 'dd.LL.yyyy');
if (dt.isValid) {
return dt;
}
return DateTime.fromFormat(dateString, 'dd.LL.yyyy HH:mm');
}
let dateString = '28.09.2022';
console.log(customParse(dateString).toJSDate());
dateString = '28.09.2022 11:46';
console.log(customParse(dateString).toJSDate());
<script src="https://cdn.jsdelivr.net/npm/luxon#3.0.4/build/global/luxon.min.js"></script>

Related

How to convert a german date string into a date correctly?

I have a string, which I want to convert to a Date;
let dateStr = "01.04.1990"
let date = new Date(dateStr);
but if I try to console log the date I get Thu Jan 04 1990 00:00:00. As you see day and month are switched but why?
How would I convert that string correctly?
You could reorder the values for an ISO date string and get the instance with this value.
let dateStr = "01.04.1990"
let date = new Date(dateStr.replace(/(.*)\.(.*)\.(.*)/, '$3-$2-$1'));
console.log(date);
In genereal Date.parse() is expecting an ISO-8601 formatted date string.
A recommendable approach would be to use a library like Luxon, as suggested here: stackoverflow

Create new Date object by using moment.js

I have string:
date = "2019/1/16 00:00 +0900"
I'm in New York (timezone -5), I want to create an Date object like that:
Wed Jan 16 2019 00:00:00 GMT+0900
I can't use javascript to convert. It will return with timezone -5.
I use moment.js:
moment.tz(date, 'Asia/Tokyo').format('YYYY/MM/DD HH:MM');
However, it's not right. Could you please help me. Thank a lot.
It will work if your date object is a moment instance:
moment.tz(moment(date), 'Asia/Tokyo').format('YYYY/MM/DD HH:MM Z')
Timezones are difficult to get right. I think an easy-to-follow and somewhat idiomatic solution is this:
const date = "2019/1/16 00:00 +0900";
// parse in any timezone
const dateMoment = moment(date);
// deliberately set the timezone in which the moment is interpreted in
const timezonedMoment = dateMoment.tz('Asia/Tokyo');
// format the moment
const formattedDate = dateMoment.format('YYYY/MM/DD HH:MM z');
Of course, you would write this in a more concise form.

Creating a Date is adding automatically one hour to my input date

let's say I have this date as input :
var _dateA = 2018-11-15T11:13:26.687Z
If I'm doing, whatever,
var _dateB = new Date(_date)
or
var _dateB = moment(_date)
I get this as result ==>
_dateB = Thu Nov 15 2018 12:13:26 GMT+0100 (heure normale d’Europe centrale)
I understood that there's timezone trouble, but how can I get a Date object or Moment object, without having this one hour more?
Wanted result => Thu Nov 15 2018 11:13:26 GMT+0100
Current result => Thu Nov 15 2018 12:13:26 GMT+0100
You need to use Date.toUTCString() that converts date to string, using the UTC time zone
var _dateA = '2018-11-15T11:13:26.687Z';
var _dateB = new Date(_dateA);
console.log(_dateB.toUTCString());
When you "output" a Date object via console.log(), alert(), etc the toString() method is used by default, converting the date object to a local timezone string for display (which is why you are seeing your date in your local time).
Parsing date strings with the Date constructor is not recommended (although, I suspect that most browsers probably handle ISO 8601 dates, like the one in your question, fairly well) - see the dateString parameter note here. So, if you need to construct a date object as well as output a date string, then you could parse the ISO 8601 string with split() using a regex character set for multiple delimiters, then construct a UTC date object with new Date(Date.UTC(...)). You could also do this with moment.js but the below should illustrate what is happening in a bit more detail.
For example:
const text = '2018-11-15T11:13:26.687Z'
const [y, m, d, hh, mm, ss, ms] = text.split(/[-T:.Z]/);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
console.log(date.toLocaleString()); // date string in local timezone
console.log(date.toUTCString()); // UTC date string
console.log(JSON.stringify(date)); // ISO 8601 date string in most browsers

needs understanding of this format of date and time

I just came across this format of start and end in the codebase which is probably the starting and ending date and time.However, I could not figure out this.
I know how to generate date and time in javascript but I need to generate it in this format to be able to fetch data from API.
Here is the format.
start : '2018-06-20T11:44:21.938Z',
end : '2018-07-20T11:44:21.938Z',
At the same time, I would like to know how to get date and time with exact this format?
It is ISO format of the date. You can use toISOString() method to achieve it:
// current date
var date = new Date();
console.log(date);
console.log(date.toISOString());
let date = new Date( Date.parse('2018-06-20T11:44:21.938Z'));
To retrieve date & time separately.
date.toLocaleDateString();
date.toLocaleTimeString()'
To convert any date object to your desired format (ISO Dates):
var date = new Date();
date.toISOString();
var date = new Date(Date.parse('2018-06-20T11:44:21.938Z'));
It's ISO 8601 format.
Check this:
https://en.wikipedia.org/wiki/ISO_8601
Have a look at toISOString() in MDN
var event = new Date('05 October 2011 14:48 UTC');
console.log(event.toString());
// expected output: Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)
// (note: your timezone may vary)
console.log(event.toISOString());
// expected output: 2011-10-05T14:48:00.000Z
That is the ISO date format.
similar to this:
How do I output an ISO 8601 formatted string in JavaScript?
Here is code to produce it.
function myFunction() {
var d = new Date();
var n = d.toISOString();
document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">convert to ISO date format</button>
<p id="demo"></p>
It is an ISO date. Check this link for some info:
https://www.w3schools.com/js/js_date_formats.asp
var istDate = new Date(); // will return: Wed Sep 05 2018 17:50:39 GMT+0530 (India Standard Time)
var isoDate = istDate.toISOString(); // will return in ISO format i.e. "2018-09-05T12:20:39.732Z"
var dateString = istDate.toDateString(); // will return in format: "Wed Sep 05 2018"
Browser console will provide suggestions for various methods of Date Object for extracting day, month, year, etc from the new Date()

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

Categories