This question already has answers here:
Convert date to specific format in javascript?
(4 answers)
Closed 5 years ago.
An API I use provides a date in the object like 2018-02-14T17:00:00. How can I convert this to make it say: Tuesday, February 14th 7:00 pm
I know how to use .getMonth() methods on a date object but is it possible to do something similar with a string in a date format like this in Javascript?
You can use momentjs to format the date object.
console.log(new moment('2018-02-14T17:00:00').format('dddd, MMMM Do h:mm a'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
You can parse the string into separated values first using String.split() method.
let rawDate = '2018-02-14T17:00:00';
let date = rawDate.split("T")[0]; //2018-02-14
let time = rawDate.split("T")[1]; //17:00:00
let year = date.split("-")[0],
month = date.split("-")[1],
day = date.split("-")[2];
let hr = time.split(":")[0],
mm = time.split(":")[1],
ss = time.split(":")[2];
Now just format these separated values using new Date(year, month, day) etc.
try this
console.log(new moment('2018-02-14T17:00:00').format('LLLL'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
JavaScript natively does not provide a way for you to stringify a date with a provided format.
To do that, you can use moment.js. Here's the specific documentation that says how to do that:
https://momentjs.com/docs/#/displaying/format/
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
How do I format a date in JavaScript?
(68 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 1 year ago.
Let's say I have a string 2021-08-13 and want to convert this to August 13, 2021. How would you achieve this as it's not a date object.
In my mind I can think of setting each numeric month to a text version of that month and re-arrange, however seeing if there are better ways of doing this.
Simple: convert the string into a Date object and use the toLocaleString function.
If you want to get rid of the timezone so the date stays the same wherever the user is you can first convert it into an ISO string, get rid of the 'Z' in the end, and then convert it back into the Date object.
const dateString = '2021-08-13'
const localeOptions = {dateStyle: 'long'}
const dateTimezone = new Date(dateString).toLocaleString('en-US', localeOptions)
const dateWithoutTimezone = new Date(new Date(dateString).toISOString().slice(0,-1)).toLocaleString('en-US', localeOptions)
console.log(dateTimezone)
console.log(dateWithoutTimezone)
Convert your string date to a JS Date Object
let strDate = "2021-08-13";
let date = new Date(strDate);
console.log(date.toDateString())
Learn more about Date object here: JavaScript Date
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 1 year ago.
I tried new Date(03/11/2015) but it didn't work but new Date(2015/3/11) does. How do I convert a string like '03/11/2015' to '2015/3/11'? I tried using date-fns with the format method but format(new Date(03/15/2015), 'YYYY/MM/DD') returns Invalid time value
Why isn't the Date constructor taking in string values in MM/DD/YYYY format?
You could use a regex replacement approach here:
var input = '03/11/2015';
var output = input.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$1/$2");
var date = new Date(output);
console.log(date);
This question already has answers here:
Format a date string in javascript
(7 answers)
Closed 2 years ago.
How do I format the date I receive from openweather api?
I currently get 2020-10-16 00:00:00 and I want 10-16-2020.
The reason I don't use moment is because I want future dates which come automatically with the 5 day forecast in the api.
You can use JavaScript's Date object.
You might save yourself time by searching a bit more before posting a question, the answer is probably already out there.
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Format JavaScript date as yyyy-mm-dd
You could try to:
Make a new date based on the date that comes from OpenWeather api
Convert it to a LocaleDateString using the 'en-US' locale. This will make the month appear before the date.
Then just split the Date String on the '/' and join in on a '-'. This will substitute the '/' with a '-'
const date = new Date("2020-10-16 00:00:00").toLocaleDateString('en-US');
const formatedDate = date.split('/').join('-');
console.log(formatedDate);
You can always use the built in Javascript Date object.
In your case you'd want to. do something like this -
const myDate = new Date('2020-10-16 00:00:00');
const date = myDate.getDate();
const month = myDate.getMonth() + 1;
const year = myDate.getFullYear();
console.log('MM-DD-YYYY', `${month}-${date}-${year}`);
If you want something more convinient and don't want to use moment you can also try some other popular date libraries. You can find some here - https://github.com/you-dont-need/You-Dont-Need-Momentjs
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
How can I convert string to datetime with format specification in JavaScript?
(15 answers)
Closed 3 years ago.
I am having date which is in mm/yyyy format. I need to compare this date with today's date. I have converted today's date.
After converting I have got date in mm/dd/yyyy format..But I need to covert it into mm/yyyy format..So that I can compare this date into, date which I am getting..Any help please.
selecteddate=05/2019 //which is in mm/yyyy format
myDate= new Date().toLocaleDateString(); //which is in mm/dd/yyyy format( I need to convert this date into mm/yyyy format and need to compare with selecteddate)
Using toLocaleDateString options
let date = new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit' })
console.log(date)
Hope this helps,
const date = new Date();
const myDate = `${(date.getMonth() + 1)}/${date.getFullYear()}`;
console.log(myDate);
You can use Moment.js, as follows:
moment().format('MM/YYYY')
import datetime
selecteddate='05/2019'
selecteddate= datetime.datetime.strptime(selecteddate, '%m/%Y')
today_dtime= datetime.datetime.now()
today_dtime.date()>selecteddate.date()
output:True
One thing note down month and year will assign as in selecteddate,But date will be 1st of respected month.
try this simple trick
You can use the following logic to compare your selected date with today's date
const selectedDate="05/2019"; // MM/YYYY
const today = new Date();
const todayString = `${(today.getMonth() + 1)}/${today.getFullYear()}`;
const matched = ( todayString === todayString );
console.log("Does your selected date matched with today's date ?",(matched ? "Matched":"Don't Matched"));
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I am trying to extract date from a string 20170901000000. new Date(string) returns Invalid Date. The date string looks pretty straightforward to me but apparently javascript doesn't take it.
What formats does javascript new Date() method take? Is there a package taking more formats of date string?
Edit: The formats are from random users. The YYYYMMDDhhmmss is only one example. The package has to be able to determine what format it is by itself and parse it.
You have to parse your date string:
parseDateString = dateStr =>
dateStr.replace(
/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$/,
'$1-$2-$3 $4:$5:$6'
);
console.log(new Date(parseDateString('20170901000000')));
Hope this helps,
you can split that string and use this..
new Date (YYYY,MM,DD,HH,MM,SS)
/* from mdn */
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
Use a propper library like Moment.js:
const date = moment("20170901000000", "YYYYMMDDhhmmss");
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
When using a number passed to the date function it must be in the format of a unix timestamp.
new Date(value): A Unix Time Stamp which is an integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).
Otherwise you need to generate a valid time string:
new Date(dateString): String value representing a date. The string should be in a format recognized by the Date.parse() method
Since your format is YYYYMMDDHHMMSS and not a unix timestamp we can use the latter dateString approach and use regex to create a valid string date:
let format = '20170901000000'
.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
console.log('format:', format)
console.log('date:', new Date(format))
Also see the [document for Javascript Date.parse][1]
Examples
new Date('2017-09-01 00:00:00');
new Date('Sept 01, 2017 00:00:00');
For more libraries you can use Moment.js or Day.js