I have a date string in variable called dateEnd like this Mon Nov 20 2017 23:59:59 GMT-0200 on my react component and I want to extract the day (20) and convert it to a number.
This is my code:
let dateEnd = rangePicker['endDate'] && rangePicker['endDate'].toString();
How can I do this?
I've tried some like this:
let dateEndNum = parseInt(dateEnd.replace(/^\D+|\D.*$/g, ""), 10);
But returns me a error, because .replace is not defined.
In addition, I want to get the initial date and the end date to calculate how many days has between those dates.
This would return a boolean.
let dateEnd = rangePicker['endDate'] && rangePicker['endDate'].toString();
What you want is something like this:
let dateEnd = rangePicker['endDate'] ? rangePicker['endDate'].toString() : '';
Your issue is not related with react. However I suggest you try out moment.js - it is a super powerful js library for handling datetime objects. In your case:
const momentDate = moment("Mon Nov 20 2017 23:59:59 GMT-0200");
const extractedDays = momentDate.date();
Although this isn't related to React, I recommend using momentjs, you can create a moment object using the date string, and one of the many functions can get you want you want.
Related
I have the following date
let api_date = '2022-03-01T00:00:00.000Z'
Now, i want to get previous 2 dates starting from api_date. Basically now i need dates as 2022-02-28T00:00:00.000Z and 2022-02-27T00:00:00.000Z
Basically for api_date of 1st March, i need previous 2 dates as Feb 28th and Feb 27th.
I tried using this below code
let t-1 = moment().substract(1, 'days')
let t-2 = moment().subtract(2, 'days')
But this only provides previous 2 dates from the present date. i.e. present date is 2nd March, so it provides previous 2 dates based of 2nd March.
how can i use moment to get my current specified date and get previous 2 dates based on that. Any advice to achieve that ? i saw the documentation of moment.js too but i didnt find a definitive answer.
You should create a date object from the date you wanna parse like this,
let api_date = '2022-03-01T00:00:00.000Z'
var dateObj = new Date(api_date);
then you can create a moment object based on the date object just like this,
var momentObj = moment(dateObj);
then if you perfom your specific logic you will get your desired result, like this
let date1 = momentObj.substract(1, 'days')
let date2 = momentObj.substract(2, 'days')
You were almost there, you need to pass your date to moment. Otherwise it defaults to current date ( as you found out ).
let t-1 = moment(api_date).subtract(1, 'days')
let t-2 = moment(api_date).subtract(2, 'days')
Here's my Scenario:
I have a value for DateTime in this Format only:
'2017-05-01T07:40:00.000+10:00'
but need this to convert to a Readable Date Time Format like this:
eg. 05/01/2017 07:40 AM
- Without Converting it to your Local Time, because if i use
var t = "2017-05-01T07:40:00.000+10:00";
var d = new Date(t); //using javascript Date object
var z = moment(t); // or using moment.js:
var d and z both have the same output like this:
Mon May 01 2017 05:40:00 GMT+0800 (Taipei Standard Time)
//05/01/2017 05:40 AM
it's minus 2 Hour in my Local Timezone GMT +8, but i don't want it to be converted that way.
i just need the exact Time which is 05/01/2017 07:40 AM
Is there other way to get my desired output in javascript?
Try use with Regex pattern /-|:|T/g for split()
var t = "2017-05-01T07:40:00.000+10:00";
var s =t.split(/-|:|T/g).slice(0,5)
var c =parseInt(s[3]) > 12 ? parseInt(s[3])-12 : s[3];
var f =parseInt(s[3]) > 12 ? 'PM' : 'AM';
console.log(s[1]+'/'+s[2]+'/'+s[0]+' '+c+':'+s[4]+' '+f);
You may refer to this post
Stop javascript Date function from changing timezone offset
It also mentioned a sample on how to use 'moment' to pinpoint the datetime to the timezone you want to show (GMT+10).
I think so this will help you.
var t = "2017-05-01T07:40:00.000Z";
var d = new Date(t); //using javascript Date object
I am trying to parse a string to javascript Date object, I tried different ways to parse it to Date but none of them seems to work. Initially I was thinking it will be easy to parse string to Date as JavaScript Date has constructor that takes a string or I would use Date.parse() method but it seems that I was wrong.
Here is string for date format-
2015-12-01 00:28:28.1271204 +01:00
What I have tried so far-
var dateCalc = new Date(str);
var dateCalc = Date.parse(str);
Please this JSFiddle - http://jsfiddle.net/D7c28/12/
Please suggest solution for this. Please let me know if I am missing something.
Thanks :)
It works fine for me:
var str = "Fri, 15 Nov 2013 09:00:00 -0600"
var date = new Date(str);
console.log(date.getDate()) // 15
date is a Date object with many methods like getDate(). Check out the documentation.
Update:
2015-12-01 00:28:28.1271204 +01:00 seems not to be a valid date for the default constructor (but works fine in node on my Mac). So I use moment.js and it works fine.
Check out the updated jsfiddle.
I'm almost sure that
var dateString = "2015-12-01 00:28:28.1271204 +01:00";
var dateCalc = new Date(dateString);
Will work (dateCalc) will have a proper date (that is, Tue Dec 01 2015 00;28:28 GMT+0100.
If you want to be a more flxeible with the solution you always can try MomentJS which gives you a lot of possibilties with format, localization and such stuff.
Moment.js is a very usefull JavaScript library which provides many functions to manipulate date formatting.
In order to create a Moment object, it is possible to parse a string simply moment("1995-12-25"); or by providing format moment("12-25-1995", "MM-DD-YYYY");.
Another feature allows us to use relative dates : moment("1995-12-25").fromNow() // 19 years ago.
However, I can not find a way to parse such a relative date. When I try moment("19 years ago") it just returns Invalid date, and it does not exist any token to properly format the date.
Is there an easy way to do this? Or is it a missing feature that should be suggested on Github?
Just found chrono wile looking to see if NLP had already been implemented in momentjs. It looks like it handles parsing NLP to a date, which can be used to create a momentjs date.
Simply pass a string to function chrono.parseDate or chrono.parse.
> var chrono = require('chrono-node')
> chrono.parseDate('An appointment on Sep 12-13')
Fri Sep 12 2014 12:00:00 GMT-0500 (CDT)
And a quick example showing how that would work
Code
const moment = require('moment')
const chrono = require('chrono-node')
let now = moment()
console.log(now)
let yrsAgo = chrono.parseDate("19 years ago")
console.log(yrsAgo)
let yrsAgoMoment = moment(yrsAgo)
console.log(yrsAgoMoment)
Output
$node test.js
moment("2017-06-30T08:29:20.938")
1998-06-30T17:00:00.000Z
moment("1998-06-30T12:00:00.000")
The only way of doing this is moment().sub(19, 'years');
What you are asking imply a Natural language processing which is whole computer science field.
There is a plugin which very recently appeared on github, which is a plugin to moment to allow this sort of parsing: https://github.com/cmaurer/relative.time.parser
I have not personally tried it, but I will shortly (found both it and this question while searching for the same thing).
What about :
moment.fn.parse = function(_relative, _format){
var _modulo = moment.normalizeUnits(_format);
return this.add(_relative, _modulo);
}
moment("30/08/2015", "DD/MM/YYYY").parse(-20, "years").format('DD/MM/YYYY'); // 30/08/1995
moment("30/08/2015", "DD/MM/YYYY").parse(-2, "week").format('DD/MM/YYYY'); // 16/08/2015
moment("30/08/2015", "DD/MM/YYYY").parse(-2, "d").format('DD/MM/YYYY'); // 28/08/2015
I wrote the plugin relative.time.parser. The original intent was to parse relative time from graphite from/until, so I was only going for the 'reverse' in time.
I will take a look at adding the 'NLP' use cases as well.
Thanks,
Chris
You can do it easily using moment plus little logic. Here it is working perfectly
function parseSincUntilDate(dateStr, now = new Date()) {
// inputs: 20 minutes ago, 7 hours from now, now, '', or UTC string
if (moment(dateStr).isValid()) return moment(dateStr).toDate();
const tokens = dateStr.split(' ');
if (dateStr.includes('ago')) {
return moment(now).subtract(tokens[0], tokens[1]).toDate();
} else if (dateStr.includes('from now')) {
return moment(now).add(tokens[0], tokens[1]).toDate();
} else if (dateStr === 'now' || dateStr === '') {
return new Date(now);
}
return moment(dateStr).toDate();
}
// to change relative date, pass it in second parameter
As of Moment.js 1.0.0 (October 2011) to current:
moment().add(7, 'days');
moment().subtract(1, 'seconds');
Works with years, quarters, months, weeks, days, hours, minutes, seconds, and milliseconds.
https://momentjs.com/docs/#/manipulating/add/
https://momentjs.com/docs/#/manipulating/subtract/
The format of my date string looks like this: yyyy-MM-ddTHH:mm:ss-0Z00
Example 1: 2010-03-05T07:03:51-0800
Example 2: 2010-07-01T20:23:00-0700
I need to create a date object using these date strings. new Date() does not work on this string.
Please help me convert these date strings into a date objects with the local timezone.
Thank you!
Edit: I am using this in Pentaho Data Integration 4.3.0.
Take my timezone as an example (AEST):
function parseDate(str_date) {
return new Date(Date.parse(str_date));
}
var str_date = "2015-05-01T22:00:00+10:00"; //AEST time
var locale_date = parseDate(str_date);
locale_date: Fri May 01 2015 22:00:00 GMT+1000 (AEST)
var str_date = "2015-05-01T22:00:00+00:00" //UTC time
var locale_date = parseDate(str_date);
locale_date: Sat May 02 2015 08:00:00 GMT+1000 (AEST)
You can use a library such as Moment.js to do this.
See the String + Format parsing.
http://momentjs.com/docs/#/parsing/string-format/
The following should parse your date you provided, but you may need to modify it for your needs.
var oldDate = "2010-03-05T07:03:51-0800";
var dateObj = moment(oldDate, "YYY-MM-DDTHH:mm:ssZ").toDate();
Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.
http://momentjs.com/docs/#/parsing/string/
Alternative
A second way of doing this is Date.js, another library that seems to parse the format just fine. http://www.datejs.com
Date String:
var strDate = "2010-07-01T20:23:00-0700";
To local time representation in native JS Date object:
var ltzDate = (new Date(strDate)).toLocaleString();