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.
Related
I am currently using angular 9 DateTime Pipe in order to format my dateTimes.
I am storing the dateTimes in database with DataTimeOffset.
When I am retrieving this dates from server are in this form: "2021-03-30T16:26:52.047+02:00"
I am using this code to apply the format to my dates:
const pipe = new DatePipe('en-Us);
const formatedDate = pipe.transform(date, 'dd.MMM.yyyy HH:mm:ss');
When I am doing this, the pipe is taking the browser time and format my date.
I know that this is the default option, if I am not sending the 3rd parameter to the transform function.
But I have a business need to show the dates as they are...but formatted in the format mentioned above,
My question is: How can I avoid the timeZone convert but still format the dateTime?
You may use var transformedDate = new Date(datepipe.transform(myDate, 'yyyy-MM-dd' + ' UTC'))
After many days of investigation, the only workaround was to use the library "Luxon".
https://moment.github.io/luxon/docs/manual/zones.html
With this library I can do something like this:
var keepOffset = DateTime.fromISO("2017-05-15T09:10:23-09:00", { setZone: true });
Which will keep the offset intact.
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>
I'm having a pretty horrid time trying to convert an 8601 into a readable format. The date shows as 'P0DT0H0M10S' and is stored in a var called timeLeft. Every article I find online tells me how to turn dates INTO the 8601 format, but not the other way around.
I tried using moment.js but that seems to revolve around the current date and not one set by my timeLeft var. How do I get this var into a user-friendly format? Thanks
Moment has a duration type:
var duration = moment.duration('P1Y2M3DT4H5M6S');
// user-friendly format
var out = duration.humanize();
snippet.log(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
First off, that's not an ISO-8601 date (not even close).
Second, momentjs does support parsing a string into a moment, with the moment("20111031", "YYYYMMDD") syntax (from their front page examples).
I'm not sure what the pattern you need would be, but maybe something like [P]D[DT]H[H]M[M]S[S].
I want to create a Date object in Javascript using this string 04/21/2014 12:00p
When passed to the constructor (new Date('04/21/2014 12:00p')), it returns Invalid Date.
I've seen other posts which manipulate the string in order to fulfill the requirements of a valid dateString, however that is not what I want. I want Javascript to recognize my date format (m/dd/yy h:mmt). In Java, something like that is simple, I imagine that there would be a similar way in Javascript.
How can I get the Date object to recognize my format?
This is trivial only when using a library like moment.js:
var dt = moment("04/21/2014 12:00p","MM/DD/YYYY h:mma").toDate();
Otherwise, you would have considerable string manipulation to do. Also you would have to account for users in parts of the world that use m/d/y or other formatting instead of the y/m/d formatting of your input string.
If this string is being sent from some back-end process, you might consider changing the format to a standard interchange format like ISO-8601 instead. Ex. "2014-04-21T12:00:00"
To manipulate the string in order to fulfill the requirements, could be a way, but you need to take care of all browser issues.
A more quick and dirty way is use moment.js library. It helps on formatting matters too.
if (String.prototype.dateFromJava == null)
{
String.prototype.fromJava = function (sDateString)
{
var aDateOrTime = sDateString.splt(" ");
var aDateParts = aDateOrTime[0].split("/");
var aTimeParts = aDateOrTime[1].split(":");
var oDate = null;
/* just get the pieces and passing them in to new Date(), return oDate */
}
}
I am trying to parse a date string i get from php through ajax call(which is irrelevant for now) using new Date().
however i keep getting wrong results.
My string is 2013-05-09 20:56:17
When i do
var something = new Date("2013-05-09 20:56:17");
alert(something.getMonth());
It keeps alerting 0
In my opinion for some reason new date cant parse this string.
Is there a way to specify the date format for new Date() in JS ?
My current solution is to import php's: date() and strtotime() and use them :
alert(date('m', strtotime("2013-05-09 20:56:17")));
This works however I have to use external js lib and I am pretty sure there is a better JS way to achieve that.
If you use slashes instead of hyphens, it works:
var something = new Date("2013/05/09 20:56:17");
alert(something.getMonth());
It's easy enough to replace any hyphens in a string with slashes first if you need to (say, if you were getting the date string from somewhere else):
var something = new Date("2013-05-09 20:56:17");
something = something.replace('-', '/');
It seems JavaScript's Date constructor doesn't recognize date formats with hyphens, or at least not that particular format.
Choose a different format specifier in PHP for your ajax dates. The format you expect and the format expected by the javascript are different.
var something = new Date("2013-05-09T20:56:17");
Note the 'T' which appears as a literal separator and marks the beginning of time per ISO 8601
Reference for various [browser] javascript date formats
W3 DateTime
Microsoft IE DateTime
Mozilla [Firefox] DateTime
Google DateJs
And lastly, the PHP date format specifier list:
PHP Date
PHP DateTime
Note the 'DATE_ISO8601'; but I suggest not using that at this time. Instead use 'DATE_ATOM' which may produce a date format more widely supported (comments suggest it makes iPhones happier and no issues with other browsers).
To use it in PHP:
$something = new DateTime('NOW');
echo $something->format('c');
echo $something->format(DateTime::ATOM);