0

Please, help me to understand, why you cannot enter any date,returns an error is NaN

https://code.sololearn.com/WDWf1H31Lbn4/?ref=app

13th Apr 2021, 10:17 PM
Тимур Завьялов
Тимур Завьялов - avatar
6 odpowiedzi
+ 2
Тимур Завьялов When you write new Date(), it can only take certain types of arguments. Otherwise, an invalid date is created. Your code works. The user has to enter valid data. Examples: Try entering May 22, 2017 12:51:00 Or 999998363837
13th Apr 2021, 10:30 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 2
The simplest way is to pass a string into prompt to ask the user to enter the right format: prompt("Please enter a date in the format...") That obviously relies on the user doing the right thing. To make things safer, you should validate the input but that's not as simple. You can try this: let date = new Date(prompt ("ask for the format you want")) // check if the date is valid if (date istanceof Date && !isNaN(date)) { // carry on with the rest of your code } else { // ask the user for the input again } You might want to do this in a while loop so that it continues to prompt the user until they meter a valid date. Personally, I think that's quite annoying and not good UX but it's good for practising your logic.
13th Apr 2021, 10:58 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 1
Тимур Завьялов I understand what you wanted now. How to convert that format to a message for the user. You can use any of these string formats to create Date objects. There are others too like Vasiliy said. 'mm.dd.yyyy' 'mm.dd.yy' 'mm-dd-yy' 'mm-dd-yyyy' 'mm/dd/yyyy' 'mm/dd/yy' Once you feel a bit more comfortable, try to implement a select (drop-down list) to get the date from the user. You will have much more control over the format that way.
14th Apr 2021, 12:15 AM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 1
CamelBeatsSnake, since the code uses the method getFullYear(), be careful with two-digit year, as the output will be different when you enter "<50" and ">=50".
14th Apr 2021, 12:41 AM
Solo
Solo - avatar
0
CamelBeatsShake, and how to request in prompt dd. mm. yyyy with this type?
13th Apr 2021, 10:37 PM
Тимур Завьялов
Тимур Завьялов - avatar
0
😂😂😂 Всё та-же тема. Упращённый формат ввода данных для обьекта Date(yyyy, mm, dd), либо так: Date(mm, dd, yyyy). В вашем случае, Date( prompt() ), можно вводить данные как через запятую, так и через точку и пробел ☺️ Код для ввода в формате "dd.mm.yyyy": [d, m, y] = prompt("dd.mm.yyyy").split(' . '); let date = new Date(y, m, d);
13th Apr 2021, 11:20 PM
Solo
Solo - avatar