Convert a string to a date with Date or Moment.js - reactjs

I have a string that I want to convert into a date to compare it to the current date and hour (local time). The string format is like this:
2020-06-09 11:25 pm
And I want to use either Date or Moment.js to format it to a Date object, but so far I haven't had any luck.
const date = new Date(`${eventDayFinish} ${eventHourFinish}`);
Prints Date { NaN }
Any help will be appreciated.

Use the moment this way.
let d = moment('2020-06-09 11:25 pm', 'YYYY-MM-DD HH:mm a').format();
console.log(new Date(d));
// Tue Jun 09 2020 23:25:00 GMT+0530 (India Standard Time)
Explanation:
Moment takes the second argument as the format of the input date string, you can give any format to it, along with the format you passed, it will return you the date object.

Related

Date/Time Formatting in React

I am working with an API that returns Dates in the format 2022-03-01T11:32:37
Created: {this.props.proposal.OPENWHEN}
Created: 2022-03-01T11:32:37
How do i format this into DD/MM/YYY 24:00:00 ?
Thanks In Advance
Something like the following should be enough:
// Example expected argument: 2022-03-01T11:32:37
function prettifyDateTime (str) {
// Splitting the string between date and time
const [date, time] = str.split("T");
// Assuming 03 is the month and 01 is the day – otherwise, those could be swapped
const [year, month, day] = date.split("-")
// Added slashes and the space before the time
return `${day}/${month}/${year} ${time}`
}
prettifyDateTime("2022-03-01T11:32:37") // '01/03/2022 11:32:37'
Otherwise, I recommend using a date library like date-fns, dayJS, or moment.
You can use the Date object to accomplish what you want. It'll also accept other date formats. Here is one place to find Date description. You also get the benefit of rejecting invalid date formats
function prettifyDateTime(str) {
let date = new Date(str);
// There's other ways of formatting this return
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

Get month and date from React moment

I have a date on Wed Dec 25 2019 05:30:00 GMT+0530. I want to format into 25 Dec
How can I do that?
const date= currentItem.date;
First convert it into moment
let date_moment=moment(currentItem.date,"ddd MMM DD YYYY HH:mm:ss ZZ")
Then convert it to required format
let req_format=date_moment.format("DD MMM")
Note: if your timeformat is 12 hour use hh. for other datetime format and timezone format check moment documentation :) Moment Docs
This snippet of code will get exactly what you want from any date entered as variable name date to dateIn.
var dateIn = moment(date, 'YYYY/MM/DD');
var month = dateIn.format('M');
var day = dateIn.format('D');
console.log(day + " " + month);

How to check if a string date has passed a certain date

I have these strings:
yy = "19";
mm = "05";
dd = "31";
These represent the creation date of a certain object in my project. This object expires after one month. How do I check if the object has expired already?
(I came across this solution but thought there might be another way to do it.)
UPDATE: the string date apparently represent the actual expiry date
I ended up using the date format "yymmdd" so I can convert it to type long and do a simple number comparison.
sprintf(buffer, "%s%s%s", yy, mm, dd);
expiryDate = atol(buffer);
// get current date of format "yymmdd" as well
// getCurrentDate() is my function that gets the date from my SDK
currentDate = getCurrentDate();
if(expiryDate >= currentDate)
{
// expired object!
}

How to change date format in Angularjs

I am facing same problem, by using above mentioned code problem is still not resolved.
My date is coming in JSON like
200515
where 20= date
05= month
15= year,
I am using the following code:-
{{200515 | date : "EEE, MMM dd"}}
but it gives me:
Thu, jan 01
but I want
Wed, May 20
Please help for the same.
You have to create a date object before using your filter because it will only formatted the date. Here your date is null.
Firstly you have to create your date using basic Date api
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
and after use the created object in your code with the filter
Your input string for your date 200015 is not a valid ISO 8601 date string. You must supply either a javascript Date object or a valid string of format such as 'yyyy-MM-ddTHH:mm:ss.sssZ' or 'yyyy-MM-ddTHH:mmZ' etc. See http://en.wikipedia.org/wiki/ISO_8601
Just use .substring() to parse your date string and build a new date object. This works with angular's date filter.
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
var date = '200515',
day = date.substring(0, 2),
month = date.substring(2, 4),
year = date.substring(4, 6),
time = '0513',
hour = time.substring(0, 2),
minute = time.substring(2, 4);
$scope.date = new Date('20' + year, month - 1, day, hour, minute);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp", ng-controller="MyCtrl">
{{date | date : "hh:mm EEE, MMM dd"}}
</div>

Angularjs + moments-js returns wrong date

i use angularjs and i want parse a string to a date my code looks like this:
var d=moment.utc("2011-10-02T22:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
var year =d.year();
var month =d.month();
var day =d.day();
$log.log("MOMENTS:"+"year: "+year+" month: "+month+" day: "+day);
the date should be "3 october 2011"
but in the log is :MOMENTS:year: 2014 month: 2 day: 6
this date is completly wrong, why is this so and what do i wrong ? i want extract the day, month and year
Here is a fiddle: http://jsfiddle.net/FGa2J/
moment.day() returns the day of the week (not the day of the month) you need moment.date() for that. moment.month() is 0 based, so you will get 9 for October. Also, it seems like moment can parse your date string just fine without specifying the format.
Code from the fiddle:
report ( "2011-10-02T22:00:00.000Z", ["yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"] );
var d = moment("2011-10-02T22:00:00.000Z");
var year = d.year();
var month = d.month();
var day = d.date();
console.log("MOMENTS:"+"year: "+year+" month: "+(month+1)+" day: "+day);
function report( dateString, formats) {
$("#results").append (
$("<li>", { text:
dateString + " is valid: " + moment(dateString, formats).isValid()
})
);
}
You're not using the correct string formatting characters.
You have: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
In moment, it would be: "YYYY-MM-DDTHH:mm:ss.SSSZ"
Note that it's case sensitive, and doesn't necessarily match formats from other languages (.Net, PHP, etc).
However - since this is the ISO-8601 standard format, it is detected and supported automatically. You should simply omit that parameter.
From the documentation:
... Moment.js does detect if you are using an ISO-8601 string and will parse that correctly without a format string.

Resources