month ago I was working on weather website, and finished it,
I have 5 content card there and each card discribes each day of weather and on top of card I have included week day, when I make API request I get date format like that 6-21-2021, I try to align this date string, to make readable for new Date() in Javascript to pull correct number of week day from Javascript Method
this is what I do
const weekDays: string[] = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday",];
//this part is included in get request
const dateFormatAPI = (response.data.list[0].dt_txt).split("-") //6-21-2021 -> ["6", "21", "2021"]
const alignedDate: string = String([dateFormatAPI[1],dateFormatAPI[2],dateFormatAPI[0]]) //"21, 6, 2021"
.replace(",", "-")
.replace(",", "-") //Output: 21-6-2021
const date = new Date(alignedDate); //putting this format in Date Method
console.log(days[date.getDay()]) //and getting current number putting this as array index and get week day
it outputs week day, But it only outputs on Windows computer, and on Android
when I let to my friened check my website on IOS, she got error instead of showing week day she was getting undefined
and I have question why happens like that? how can I fix it?
if you use IOS right now, you can check on your own this website Weather Website
Parsing a string to create another string that is parsed by the built–in parser is not a good idea, see Why does Date.parse give incorrect results?
"21-6-2021" is not a format supported by ECMA-262 so parsing is implementation dependent and iOS treats it as an invalid date.
A library can help, but isn't necessary. To parse the string try:
let s = '6-21-2021';
// Split on non–digit character
let [m, d, y] = s.split(/\D/);
// Use the Date constructor
let date = new Date(y, m - 1, d);
console.log(date.toDateString());
console.log(date.getDay());
console.log(date.toLocaleString('default',{weekday:'long'}));
Related
I'm using Javascript's toLocalDateString method to get the date of the user on their local system time.
However the output format of the function is different across windows and mac (using chrome browsers on both):
On Windows
On Mac
As you can see on windows we get format m-dd-yyyy whereas on mac it's dd-mm-yyyy. This is causing issues in my code as I need to display it in a common format using substr on the resulting output and fetching year, date and month separately.
Is there any way to force this to output in one particular format only or is there any other reliable way to get system's local date (I only need date not the time)
You will have to pass locals argument as below:
// US English uses month-day-year order
console.log(date.toLocaleDateString('en-US'))
// British English uses day-month-year order
console.log(date.toLocaleDateString('en-GB'))
Check reference link -
toLocaleDateString
There is no guarantee whatsoever how the output of toLocaleDateString() will look on a particular browser on a particular system. So if you need a specific format, you must either create it yourself or use some library.
If you just need separate year, day and month of the current date, why not just use the respective methods on the Date() object?
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() +1; //month count is 0-based
const day = today.getDate();
var date= new Date();
var formatDate;
if(navigator.appVersion.indexOf("Win") != -1){
formatDate= date.toLocaleDateString('en-GB');
}
else{
formatDate= date.toLocaleDateString();
}
console.log(formatDate);
For example, I have this string "2020-09-09T21:00:14.114-04:00"
I grab this from my database and in its current form, it is a string. my goal is to have it display
4 PM instead of the long string of jibberish
is it possible to accomplish this?
I was thinking of possibly creating a new date object like
let test = new Date('2020-09-09T21:00:14.114-04:00').
but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible
edit: i would like the desired output to be the hour:minute and then am/pm
ex 10:15pm
You can do that by parsing the date from your database using Date.parse().
Then you can get the time or whatever you need using date.toLocalTimeString() in your case.
let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();
console.log(time); // --> "4:00:14 AM"
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here's some useful resources MDN Date.parse()
MDN Date.toLocalTimeString()
You can do as following way.new Date() is used to get the current date and time.
var today = new Date();
var time = today.getHours();
if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I have this
let d = new Date("03-08-2018"); //dd-mm-yyyy
console.log(d.getMonth()); // returns 02, I want 07
I have my date in dd-mm-yy. The getMonth() thinks I'm using mm-dd-yy.
How do I get correct month and date.
Your date format is not standard, and I strongly recommend not to use such code on a client web code, because how it behaves would be client-dependent.
EDIT (thx RobG) : Don't use the builtin parser new Date(), this will get you into trouble depending on the client timezone, even if you use a proper format where the month seems to be correctly recognized.
You'll have to create some function to parse the string yourself and create a Date object with year, month and day manually set, that would be the safe way.
Example of manual parsing :
let regex = /^(\d{2})-(\d{2})-(\d{4})$/; // each parsing group is day-month-year
let date = '03-05-2018';
let match = regex.exec(date);
let month = +match[2] - 1; // starting at 0, remove -1 if you want 1-based month number
console.log(month); // returns 4 in this example '03-05-2018'
(of course you should also put some guards if the string is not matching the correct format)
JS Date give the month starts with 0. So Try this below for getting month from date
let d = new Date("03-05-2018"); //dd-mm-yyyy
console.log(d.getMonth()+1);
if you want 4, then you should add +2 ( but i am not sure why you want 4)
let d = new Date("03-05-2018"); //dd-mm-yyyy
console.log(d.getMonth()+2);
myDate2 = "6.2014"
var date2= new Date(myDate2);
Here myDate2 does not contain days. It contains only year and month, I want to alert(date2), displays date error.
How to remove and output year and month.
In short I want to process date having format (mm.yyyy) instead of (dd.mm.yyyy).
If you simply want to parse "6.2014" to a Date, then split the string on the period "." and pass the parts to the Date constructor in the right order (year, month, day). Subtract 1 from the month as they are zero based (0 = January, 1 = February, etc.).
MDN is a good resource.
function parseMY(s) {
var b = s.split(/\D/);
return new Date(b[1], b[0]-1);
}
document.write(parseMY('6.2014'));
If you just want to reformat the string, then split it into its parts and reformat as a string:
document.write('1/' + '6.2014'.split('.').join('/'))
There are many libraries, large and small, that can help with parsing but if you only need to deal with a single format, a two line function should suffice (or a couple more lines if validation is required).
I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.
How do i get the exact date i have in var date in get date and getmonth function? Please help
The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
var spl = str.split('/');
return new Date(spl[2], spl[1] - 1, spl[0]);
}
or you will have to use external libraries like Moment.js.
Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();
Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first
you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.
Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.
// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && b[1] == d.getMonth()? d : new Date(NaN);
}
document.write(parseDMY('12/02/1994'));