MomentJS - convert YYYYMMDD and HH:MM to YYYY-MM-DDThh:mm:ss - momentjs

I get two separate time and date values from my API.
date: 20190404
time: 09:30
I want to combine the two in one acceptable format, such as YYYY-MM-DDThh:mm:ss.
I have tried the following:
moment(data[i].date + 'T' + data[i].time).valueOf()
but I get the following error in the console:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
and the value in my array shows as 'NaN'
Thanks!

Concatenate the date and time without space and add the format as the second parameter of moment()
var moment = require("moment")
var data = {date: '20190404',
time: '09:30'}
var joined = `${data.date}${data.time}`
console.log(moment(joined, 'YYYYMMDDh:mm:ss').format())
// "2019-04-04T09:30:00+01:00"

Related

How to convert the UTC date into local date in Moment.js?

I have a date in this format "2020-12-16T02:48:00" that came from the server. How can I convert this into local date and time? I tried some code but couldn't succeed.
Below is the attempt that I had made in angular after receiving date from the server.
response.data.map(date=>{
var centralDate = moment( date).zone("-06:00");
date = moment(centralDate).local().format('YYYY-MM-DD hh:mm:ss');
})
If indeed the value is in UTC (as per the title of your question), and it looks like "2020-12-16T02:48:00", and you want to convert it to local time, then you should do the following:
moment.utc(date).local().format('YYYY-MM-DD HH:mm:ss');
That does the following:
Parses the input in terms of UTC
Converts it to local time
Formats it as a string in the given format
Note also that you had hh in your original format. That is for hours in a 12-hour time format and thus you shouldn't use it without also using either A or a to indicate AM/PM or am/pm. Otherwise HH is for hours in a 24-hour time format.
If your issue is that the timezone doesn't change you can resolve using utcOffset (https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/09-utc-offset/) in this way:
response.data.map(date=>{
date = moment( date).utcOffset(-360);
})
Where 360 is the conversion fo the hours in minutes
var d= new Date();
d = new Date(d+ "Z")
I am not an expert in angular but I guess the trouble in your date is the word “T”. May be using string removal function you can remove the word “T” and then it becomes a proper date time value?

Converting Datetimes returns Null

I'm trying to convert a datetime that looks like this: 2017-09-19T07:00:00-07:00 into EST, but i keep getting Null values when using the hive built in UTC conversion.
I've tried using a regular expression to parse the date:
date_format(from_unixtime(unix_timestamp(2017-09-19T07:00:00-07:00, "yyyy-MM-dd'T'HH:mm:ss")
- (cast(regexp_extract(regexp_extract(2017-09-19T07:00:00-07:00, '(-[0-9][0-9]:[0-9][0-9])$', 1),'(-[0-9][0-9])',1) as int)*3600) -18000),'YYYY-MM-dd HH:mm')
but that's not good, since there's an hourly difference based on the time of year.
I've also tried:
FROM_UTC_TIMESTAMP(UNIX_TIMESTAMP(2017-09-19T07:00:00-07:00, "yyyy-MM-dd'T'hh:mm:ss:SSS'ZZZZZ'") * 1000, 'EST')
and
FROM_UTC_TIMESTAMP(UNIX_TIMESTAMP(2017-09-19T07:00:00-07:00, "yyyy-MM-dd'T'hh:mm:ss:SSS'Z'") * 1000, 'EST')
but that appears to not work either. What am I doing wrong?
I think that this method needs the date as a string like this:
date_format(from_unixtime(unix_timestamp('2017-09-19T07:00:00-07:00', "yyyy-MM-dd'T'HH:mm:ss")
Normally, the date formats are for strings, not for integers or numbers.
I found the answer on my own by combining the two ways of running the query.
date_format(
FROM_UTC_TIMESTAMP(
(unix_timestamp('2017-09-19T07:00:00-07:00', "yyyy-MM-dd'T'HH:mm:ss")
+ (cast(
regexp_extract(
regexp_extract('2017-09-19T07:00:00-07:00', '(-[0-9][0-9]:[0-9][0-9])$',1),'(-[0-9][0-9])',1) as int)
*-3600)
)*1000 ,'America/New York')
,'YYYY-MM-dd HH:mm:ss')
You are getting NULL because the pattern (format of the date and time) you have provided is not matching with the actual date time value. Correcting the date time format in your query would resolve this issue:
select from_unixtime(UNIX_TIMESTAMP("2017-09-19T07:00:00-07:00", "yyyy-MM-dd'T'HH:mm:ssXXX"), "yyyy-MM-dd HH:mm:ss");
Check out this link to know more about the date time patterns: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Format hours, minutes and seconds with moment.js

I get this value from my backend service: 171054. It represents hh:mm:ss. But when I use the formatting options from the docs it gives me back 00:00:00.
Things I've tried:
moment('171054').format('hh-mm-ss')
moment('171054').format('HH-mm-ss')
moment('171054').format('HH-MM-SS')
You are confusing format option with parsing option. Since your input string is not in ISO 8601 format, you have to specify format when parsing.
Here a working example for your use case:
var mom = moment('171054', 'HHmmss');
console.log(mom.format());
console.log(mom.format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
I am not sure if momentjs can read that as date since there is no identifier. I would suggest changing the value for example you have 171054, get each 2 digits since you sure that this is represent as hh:mm:ss then add identifier between then like ":" or "-" then try us momentjs formatting again.

moment.js and deprecated warning. timestamp to moment date object

I've read thru various posts on here in regards to similiar issues but none have solved my problem.
I manipulate the moment.js date object, and then store it as timestamp.
BUT, when I try to read in that timestamp again, I get that deprecated warning.
""Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info."
I've tried toDate(), format(), moment(myTimeStamp, 'ddd, DD MMM YYYY HH:mm:ss ZZ'); --> all generate the warning...
So, for example, my timestamp will look like this:
const timestamp = '1458586740000'
when I read that back and try to parse out the month/day/year, then the hour/min am/pm, etc... I need to get that timestamp into a moment.js object. Nothing is working for me. Any ideas.
How can I get this timestamp: '1458586740000', into a moment.js object so I can extract date date from it as I need?
EDIT: this is how I am storing the timestamp. So I would need to retrieve it from this.
let timeStamp = Moment(state[_Date])
.add({ hour: state[AMPM] === 'PM'
? +state[Hour] + 12
: state[Hour] ,
minute: state[Min] }).format('x')
The X token indicates a unix timestamp in seconds, and the x token indicates a unix millisecond timestamp (offset).
You appear to have a millisecond timestamp, so you would make a moment out of it by doing the following:
var a = moment('1458586740000', 'x')
It works without ' as well:
var a = moment(1458586740000, 'x')
You can also not specify the x and it should work:
moment(1458586740000)
Because you have a unix offset (milliseconds), not a unix timestamp (seconds), moment.unix is not what you want.
Then you can do the following:
a.format()
"2016-03-21T13:59:00-05:00"
Or you can use any of the other formatting tokens listed here to output whatever result you would like: http://momentjs.com/docs/#/displaying/format/
Based on the code you presented, I think you may be having problems because your timestamp is stored as a string (in ''). Parsing as a string causes an invalid date error, because it attempts to match ISO 8601 format and fails. Specifying that 'x' token will cause it to assume unix offset and work correctly.

Convert JavaScript DateTime to UTC with no milliseconds

Right now I'm trying to parse a date that's written in a human-readable format into a DateTime String that a SharePoint list will accept. In order to do this I've determined that I need a String in a format similar to ISO that looks like: 2007-08-20T00:00:00Z. It seems that SharePoint only accepts DateTimes that are in UTC with no milliseconds included (for whatever reason, SharePoint gives errors and won't accept the DateTime when you include the milliseconds), so I need to convert my local time into a UTC time before converting it to the ISO string.
Here's the process that the code below is using.
First I use DateJS to parse my human-date into a JavaScript Date.
(Works fine, but apparently DateJS has been abandoned, so maybe I
should change this to use MomentJS.)
Next I tried to create a new
moment in UTC. (This line is very, very wrong, and crashes my
program.)
Then I have SPServices convert it into an ISO. SPServices drops the milliseconds off the DateTime so that SharePoint will accept it. (Works
fine).
I'm sure there has to be a more elegant/working way to achieve this, instead of stitching together 3 different libraries. I'm just not sure what it is.
var jScriptStartDate = Date.parse("6/29/2014 8:30am"); //JS Date
var jScriptStartDateUTC = moment(jScriptStartDate).utc(); //local date to UTC.
var startDate = $().SPServices.SPConvertDateToISO({ //Sharepoint ISO 8601 format
dateToConvert: jScriptStartDateUTC,
dateOffset: "" //Sharepoint dates only accept UTC times, aka no dateOffset.
});
newItem.set_item('EventDate', startDate); //EventDate is internal for StartTime
You can just use moment.js, and this is all in the documentation.
moment('6/29/2014 8:30am','M/D/YYYY h:mma').toISOString()
This assumes all of the following:
The source value is in the user's time zone (that is - the time zone of the machine where the JavaScript code is running)
The input will always be in the specified format
It's also worth mentioning that if you put a space before the "am", that most modern browsers can do this natively without any library:
new Date('6/29/2014 8:30 am').toISOString()
If you take that approach, realize that the date parts are ordered according to the users locale, which might be m/d/y, or d/m/y or y/m/d.
Also, you said in the title "... with no milliseconds", but didn't elaborate on that in your question. I'm fairly certain you can pass the milliseconds without issue. There's no good reason to go out of your way to remove them. But if you must, then that would be like this with moment:
moment('6/29/2014 8:30am','M/D/YYYY h:mma').utc().format('YYYY-MM-DD[T]HH:mm:ss[Z]')
I ended up adjusting this code to use the updated DateJS (https://github.com/abritinthebay/datejs/) and a custom function I made called .toShortISOString().
The process is down to 3 lines:
var jScriptStartDate = Date.parse("6/28/2014 8:00am"); //convert to Javascript Date
var startDate = jScriptStartDate.toShortISOString(); //convert to Sharepoint ISO format (UTC with no milliseconds)
newItem.set_item('EventDate', startDate); //Strangely the internal name for Start Time is EventDate
.toShortISOString()'s main change is the removal of milliseconds, since SharePoint doesn't like milliseconds. It's code looks like this inside of the date.js file:
if ( !$P.toShortISOString ) {
$P.toShortISOString = function() {
return this.getUTCFullYear() +
"-" + p(this.getUTCMonth() + 1) +
"-" + p(this.getUTCDate()) +
"T" + p(this.getUTCHours()) +
":" + p(this.getUTCMinutes()) +
":" + p(this.getUTCSeconds()) +
//Remove the milliseconds.
//"." + String( (this.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) +
"Z";
};
}
If you're trying to add this to date.js, make sure you have the latest version from the link above, then search the file for toISOString and place the code right below the handler for toISOString.

Resources