I would like to convert a date with momentjs, the date is on this format:
2021-10-10T00:00:00+02:00
In react js I do:
moment('2021-10-10T00:00:00+02:00').format('dd/mm/yyyy');
And that return me "invalid date"
Have you got any idea about this error ?
Just have the format specified inside the moment constructor. Check the snippet below.
For different formatting options, check their docs https://momentjs.com/docs/#/displaying/format/
const date = "2021-10-10T00:00:00+02:00";
const formatted = moment(date, "YYYY-MM-DD hh:mm:ss+ZZ").format("DD/MM/YYYY");
console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
Check this codesandbox which seems to be working with your input. Check if your import of moment has an issue.
CodeSandbox
Also note that if you want to format month it should be capital M - moment("2021-10-10T00:00:00+02:00").format("dd/MM/yyyy")
You code is work for me. Please check your date input is same as you type.
var time = moment('2021-10-10T00:00:00+02:00').format('DD/MM/YYYY');
$("body").text("The time is: "+time+".");
result:
The time is: 10/10/2021.
If you know the format of an input string, you can use that to parse a moment.
moment("2021-10-10T00:00:00+02:00", "YYYY-MM-DDTHH:mm:ss+-HH:mm");
If a time part is included, an offset from UTC can also be included as +-HH:mm, +-HHmm, +-HH or Z.
2013-02-08 09+07:00 # +-HH:mm
2013-02-08 09-0100 # +-HHmm
2013-02-08 09Z # Z
2013-02-08 09:30:26.123+07:00 # +-HH:mm
2013-02-08 09:30:26.123+07 # +-HH
Moment Docs - Parse - String
Related
I'm struggling for hours with this seemingly trivial issue.
I have a antd datepicker on my page.
Whenever I choose a date, instead of giving me the date I chose, it gives me a messy moment object, which I can't figure out how to read.
All I want is that when I choose "2020-01-18", it should give me precisely this string that the user chose, regardless of timezone, preferably in ISO format.
This is not a multi-national website. I just need a plain vanilla date so I can send it to the server, store in db, whatever.
Here are some of my trials, so far no luck:
var fltval = e;
if (isMoment(fltval)) {
var dat = fltval.toDate();
//dat.setUTCHours(0)
fltval = dat.toISOString(); // fltval.toISOString(false)
var a = dat.toUTCString();
//var b = dat.toLocaleString()
}
It keeps on moving with a few hours, probably to compensate for some timezone bias
UPDATE 1:
the datestring is data-wise correct. But its not ISO, so I cant use it correctly. I might try to parse this, but I cannot find a way to parse a string to date with a specific format.
UPDATE 2:
I also tried adding the bias manually, but for some reason the bias is 0
var dat = pickerval.toDate()
var bias = Date.prototype.getTimezoneOffset()// this is 0...
var bias2 = dat.getTimezoneOffset()// and this too is 0
var d2 = new Date(dat.getTime()+bias)
var mystring= dat.toISOString() //still wrong
Thanks!
Javascript date functions can be used,
I assume you are getting in 2022-01-03T11:19:07.946Z format then
date.toISOString().slice(0, 10)
to 2022-01-03
There are 2 ways to get the date string:
Use the moment.format api:
date.format("yyyy-MM-DD")
Use the date string that is passed to the onChange as second parameter
Here is a Link.
I am assuming your code snippet is inside the onChange method. This gives you a moment and a date string to work with (the first and second parameters of the function respectively).
You have a few options. You could set the format prop on the DatePicker to match the format of the string you want. Then just use the date string. Or you can use the moment object as Domino987 described.
I am using moment.js and getting this error:
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.
Arguments: [0] _isAMomentObject: true, _isUTC: false, _useU
In my react component I have:
const sortTasks = (first, second) => moment(first.endDate).diff(second.endDate);
The first.enddate=‘20 dec 2018’
How can I avoid this warning in the console?
One alternative is to inform moment.js about the date format used, by providing a second parameter to the moment function.
The format of "20 dec 2018" is DD MMM YYYY".
If you have both dates in the same format, you should write
const sortTasks = (first, second) =>
moment(first.endDate, "DD MMM YYYY").diff(moment(second.endDate, "DD MMM YYYY"));
Note that the other date is also explicitly transformed to a moment, since it is expressed in a non-standard format.
You can check the details in the moment.js documentation about parsing.
If you want to find out the difference expressed in days, or in e.g. years / months / days, you can use moment.duration. Check the moment.js documentation about this feature.
E.g. to obtain the number of years, months and days between two dates, say date1 and date2, we could proceed as follows (assuming date1 is before date2):
const theDuration = moment.duration(date2, date1);
const yearsElapsed = theDuration.years();
const monthsElapsed = theDuration.months();
const daysElapsed = theDuration.days();
Hope it helps - Carlos
I have a date formatted as a ISO-8601 string: overview.startTime = "2017-05-09T08:00:00Z"
I want to display this on my page and I have used the following code:
Dagens arbetspass {{overview.startTime | date:'dd-MMM'}}
This is displayed as "Dagens arbetspass 09-May". My problem is that this is a Swedish site, and in Sweden we don't start the month names with an uppercase character. Also May is written "maj" (j in the end and not y). I tried to add the timezone like this
Dagens arbetspass {{overview.startTime | date:'dd-MMM':'Europe/Stockholm'}}
but that did not change the output. In fact, most months are spelled differently in Swedish. Any suggestions?
Just use the javascript "toLocaleDateString" method to resolve the concern. The method takes two arguments which are 'locale' and 'options'.
Locale will be "sv-se" for swedish.
Options will provide the format to your string. For example -var options = { weekday: "long", year: "numeric", month:long",day:"numeric" };
var d = new Date("2017-05-09T08:00:00Z");
date.toLocaleDateString("sv-se", options)
Here's a plunker https://plnkr.co/edit/G2IL5Zv0OAcVRMZS9HB7
I have an application where I need to show the date in UI like DD-MM-YYYY hh:mm:ss and again this date to timestamp.
What I have tried:
$scope.dateForUI = moment().format("DD-MM-YYYY hh:mm:ss");
Here I am getting the expected result. But I need timestamp of $scope.dateForUI as well. So I have tried
$scope.dateInTimestamp = moment().unix($scope.get_date_line);
But the console output shows the 1970 date in $scope.dateInTimestamp
My question is how I format my current date and assign it to a variable and again how to get the timestamp for this particular time.
Another thing is it possible to store the time of any timezone in to my $scope.dateForUI variable using moment.js? I need to show the IST time in every browser location.
Very new to moment.js, any help would be appreciated. Thanks in advance.
Try this:
$scope.dateInTimeStamp = moment().unix();
You can use moment-timezone to get values in fixed timezone. For example:
moment.tz("Asia/Kolkata")
Use moment.unix(Number) to get moment object from seconds since the Unix Epoch
Moreover you can use valueOf() to get milliseconds since the Unix Epoch from moment object and .unix() to get seconds.
Here a snippet to show how moment-timezone works and how you can use unix():
// basic angular mock
var $scope = {};
// Current time in India (moment object)
var momNow = moment.tz("Asia/Kolkata");
// Current time in India formatted (string)
$scope.dateForUI = momNow.format("DD-MM-YYYY HH:mm:ss");
// Current time in India as seconds from 1970 (number)
$scope.dateInTimestamp = momNow.unix();
console.log($scope.dateForUI);
console.log($scope.dateInTimestamp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>
This is input format:
yyyy:MM:dd'T'HH:mm:ss'Z' (Coming as a string from json service)
Required output format:
dd-mmm-yyyy
I have tried with {{txnDate | date:'dd-mm-yyyy'}}
but it is not working..
What is the format you are following for your date?
A quick var a = new Date(); a.toISOString(); in console will give you something like "2015-02-19T13:30:13.347Z". The formatted string you are receiving is not following any standard and I am afraid parsing it to date will result in Invalid Date in most of the browsers.
So you can either
Get your Date in proper format.
Make the best use of whatever is available. You can use split to break your string into individual components.
Something like:
var a = "yyyy:MM:dd'T'HH:mm:ss'Z'" //Replace with actual string
b=a.split(':') will result in ["yyyy", "MM", "dd'T'HH", "mm", "ss'Z'"] giving you year and months in b[0] and b[1].
For date, you can use b[2].substring(0,2) to give you dd.
You have all date components(apart from time components, which you don't need anyway) as string.
Either use them directly(as a string) or make a date object using these components(since you want month in MMM format).
$scope.txnDate = new Date(b[0]+'/'+b[1]+'/'+b[2].substring(0,2));
I am sure there are more ways to optimize this. Comment if this doesn't work for you, will try to elaborate more.