moment js cannot change date string to new format - javascript

I have the following HTML:
<strong id="ut-open-date">27/06/2014</strong>
and I want to read the text/innerhtml and convert its format to "YYYY-MM-DD" so I can insert it into MySQL table. I am using the moment.js library and my code is below:
var CreateDate = moment(jQuery('#ut-open-date').html()).format("DD/MM/YYYY");
CreateDate = moment(CreateDate).format("YYYY-MM-DD");
But the code changes 27/06/2014 to 2016-06-03 and I cannot work out why.
I also tried this code with the same result.
var CreateDate = moment(jQuery('#ut-open-date').html()).format("YYYY-MM-DD");
Any help is appreciated.

If we break down your code step by step you can see where it is going wrong:
var CreateDate = moment(jQuery('#ut-open-date').html())
This part uses the default constructor to try to parse the date, this is unreliable at best and has been deprecated. So moment is trying to guess what the date format is here.
.format("DD/MM/YYYY");
This is taking what ever was read in step 1 and trying to turn it into a string with the format of DD/MM/YYYY
CreateDate = moment(CreateDate)
Now you are parsing again without specifying the format so moment is doing it's best to guess
.format("YYYY-MM-DD");
Now you have told it to turn whatever it guessed the date to be into a string with the format YYYY-MM-DD
Do this instead:
var CreateDate = moment(jQuery('#ut-open-date').html(), 'DD/MM/YYYY').format('YYYY-MM-DD');
The moment(dateString) form is deprecated you should use the form moment(dateString, expectedFormat) instead.
See moment documentation here: http://momentjs.com/docs/#/parsing/string-format/
Thanks to athms for link

The problem is you need to tell moment.js what format for date string you want parse by specifying second parameter. See all the supported format. If your format is not listed (See the Open Issue for NON-ISO strings), you need to specify the date format parameter.
moment( jQuery('#ut-open-date').html(), "DD/MM/YYYY" )
DEMO

I solved it by using split as follows:
var CreateDate = jQuery('#ut-open-date').text();
var DateArray = CreateDate.split('/');
CreateDate = DateArray[2] + '-' + DateArray[1] + '-' + DateArray[0];

Related

How to convert an invalid date string to Javascript date

I fetch invalid date strings from the REST API but i may not fix the REST API. How can i format an invalid date strings like that "20180517T010237" ?
I tried to use moment for that, but i couldnt succeed.
let date = moment("20180517T010237", "YYYY-MM-DD T HH.mm.ss").toDate();
is there any easy way to do that?
The second string you pass moment is the format of the string you're parsing. Your format string has - and spaces that aren't in your input. Remove them:
let date = moment("20180517T010237", "YYYYMMDDTHHmmss").toDate();
Note that it will be parsed in local time. If you want UTC instead, use moment.utc:
let date = moment.utc("20180517T010237", "YYYYMMDDTHHmmss").toDate();
Example:
let date = moment("20180517T010237", "YYYYMMDDTHHmmss").toDate();
console.log(date);
date = moment.utc("20180517T010237", "YYYYMMDDTHHmmss").toDate();
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Check if start datetime and end datetime are valid in momentjs

Im new to momentJs so I need a bit of help here. I am building a form where the user can send in their availabilities for a certain work period. So in the form you have a startDate, startTime, endDate and endTime. Due to the api that I have to use from a client we have to send the date like this (example) "2015-06-17T14:24:36" (with the 'T' in the middle). Currently I receive the date and the time seperate from eachother but merging them together in the end so it fits the api's way of reading date.
Now my question is as follow. I have to create a check where I can see if the input startdate-time and enddate-time are valid. For example the startdate always has to be a date BEFORE the end date (pretty logic right). But is there an easy way to do this in momentJS?
Or should I use another method?
Thanks in regard and if my question is not quite clear please let me know so I can provide extra information!
NOTE: in the end it should be something like this:
var start = "2017-06-17T14:24:36"
var end = "2017-07-03T14:24:36"
Function that checks if the start and end dates are valid
Result = true
If you simply have to check that startDate is before endDate you can use isAfter.
Here a working sample:
var start = "2017-06-17T14:24:36";
var end = "2017-07-03T14:24:36";
function checkDate(start, end){
var mStart = moment(start);
var mEnd = moment(end);
return mStart.isBefore(mEnd);
}
console.log(checkDate(start, end));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
In my first example I'm using moment(String) parsing that accepts input in ISO 8601 format.
If you need to parse non ISO 8601 format you can use moment(String, String) specifying input format (e.g. var mStart = moment(start, 'DD-MM-YYYYTHH:mm:ss');).
If you have to support multiple formats you can use moment(String, String[]). As docs states moment(String, String[]):
Prefer formats resulting in valid dates over invalid ones.
Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
Prefer formats earlier in the array than later.

Get date time in specific format in moment js

I am trying to get the date time in moment js in this format :
2016-12-19T09:43:45.672Z
The problem is I am able to get the time format as
2016-12-19T15:04:09+05:30
using
moment().format();
but I need the format as the first one [like .672Z instead of +05:30]. Any suggestions would be of great help.
From the documentation on the format method:
To escape characters in format strings, you can wrap the characters in square brackets.
Since "Z" is a format token for the timezone, you need to escape it. So the format string you are after is:
moment().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
As #VincenzoC said in a comment, the toISOString() method would also give you the format you are after.
Use moment.utc() to display time in UTC time instead of local time:
var dateValue = moment().utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';
or moment().toISOString() to display a string in ISO format (format: YYYY-MM-DDTHH:mm:ss.sssZ, the timezone is always UTC):
var dateValue = moment().toISOString();
Try this
const start_date = '2018-09-30';
const t = moment(start_date).utc().format();
console.log(t);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
var dateTime = new Date("2015-06-17 14:24:36");
dateTime = moment(dateTime).format("YYYY-MM-DD HH:mm:ss");
Try this. You should have the date in the correct format.

MomentJS change the format from YYYYMMDD

I have this format of date YY which looks like 20141229 I'm trying to get it into Timestamp format
I tried moment(date).format('x') but I get "Invalid date", not sure how to make this done, any help please ?
thanks!
moment constructor takes format as second parameter, so moment('20141229', 'YYYYMMDD') will give you valid moment object. and calling .unix() should give you timestamp.
Docs
Try separating segments with a space, for example
var date = "2014 12 29"
var stamp = moment(date).format("x")

Parse month text using parseDate utility method

I'm having trouble parsing a month year string into a date when using the jquery ui 's utility method $.datepicker.parseDate(format, string, settings). ( https://api.jqueryui.com/datepicker/ )
When I use it like
var dt = $.datepicker.parseDate('MM yy', 'January 2011');
I expect it to return a date which equals new Date(2011,00,1), but instead I get an invalid date. Does jqueryui's parseDate support full date string parsing? I can't really find any good docs on this. I expected it to support the full month parsing because the datepicker is able to display it in full month format. I've set up a fiddle* to demonstrate my problem. The core code from the fiddle is below.
*http://jsfiddle.net/mouseoctopus/fvrpG/
var text = $('#dateText').val();
var format = $('#dateFormat').val();
$('#instructions').text('Parse the date [' + text + '] using the format [' + format +']');
try{
var dt = $.datepicker.parseDate(format,text);
$('#result').text(dt);
}catch(exception){ }
So my question is.. it possible to parse a full month text using the parseDate?
I can't speak for jQuery parseDate, but you can use a native JavaScript Date.parse with the full month. The JavaScript function requires a full date though, so you'll need to add 1 in front of the date. It returns a timestamp which you can use it to create a new date.
You can find complete documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Example
alert(new Date(Date.parse('1 January 2011')));

Categories

Resources