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.
Related
How can I change hour and minute values to an existing Date variable?
formProps.date: existing Date type variable generated from a date picker that I want to use year value only.
formProps.hour: The hour value that user input separately.
formProps.minute: The minute value that user input separately.
Those three values are to be combined into a new Date variable 'dateWithTime', but it throws an error during copying the date values.
It this a wrong way to copy a Date variable? or is there any better way to make it?
const dateWithTime = new Date(formProps.date.getTime());
dateWithTime.setHours(formProps.hour, formProps.minute);
==== edit ====
the log of
console.log(formProps.date.toLocaleString());
console.log(typeof(formProps.date));
I don't know why your code above doesn't work but the below code worked for me. Could u try to use:
const dateWithTime = new Date(formProps.date.toLocaleString());
(I know it is not an comprehensive answer but I couldn't add a comment due to my reputation :/ )
This is the first time I've asked for help, so apologies if I've got the format or level of detail wrong.
I want the datepicker dates to change their background color for all dates that match a set of dates in an array of dates (highlight_dates). My code works with a manually entered array but NOT for programmatically entered dates.
How I compare dates
To check if a date is in the array I use ‘inArray’ (L11 in the following code):
1. $('#calendar').datepicker({
2. beforeShowDay: function(date){
3. var month = date.getMonth()+1;
4. var year = date.getFullYear();
5. var day = date.getDate();
6. // Change format of date
7. var newdate = day+"-"+month+'-'+year;
8. // Set tooltip text when mouse over date
9. var tooltip_text = "Results available for " + newdate;
10. // Check date in Array
11. if(jQuery.inArray(newdate, highlight_dates) != -1){
12. return [true, "highlight", tooltip_text ];
13. }
14. return [true];
15. }
16. });
(L12 “highlight” calls CSS formatting)
This works OK when I use an array that I create manually (type in) as in:
var highlight_dates = ['10-9-2019','16-5-2019', etc];
All the dates that correspond to the dates in the array change their background color in datepicker - but when I use JSON to get the dates programatically (from an external directory) none of the datepicker dates change color.
How I get the dates from an external directory
I use the following code to get the dates from the directory (calling perl code as in in L4):
1. function getResults() {
2. $.ajax({
3. type: 'POST',
4. url: 'getResultsFilenames5.pl',
5. success: function(res) {
6. //alert("reached L37 and JSON data is : " + res.result);
7. //localStorage.setItem('dateArray', JSON.stringify(res.result));
8. localStorage.setItem('dateArray', res.result);
9. var resultDates = localStorage.getItem('dateArray')
10. //var resultDates = JSON.parse(localStorage.getItem('dateArray'));
11. },
12. error: function() {alert("something didn't work!!");
13. }
14. });
15. }
The results are placed in localStorage (L8) so that they can be retrieved when needed.
The results I'm getting
When I display the dates (L6) - THE OUTPUT FROM res.result - they look like this:
23-05-2019,07-10-2019,20-06-2019,01-06-2019,30-05-2019,29-04-2019,,25-04-2019,03-10-2019,16-05-2019,,17-06-2019 (no square brackets or apostrophes).
However, with the addition of square brackets, and apostrophes in the perl code (which retrieves the dates) the array of dates look exactly like the manual array when I display them using an ‘alert’ (L 6), so I think that the problem is not to do with the programming but more likely a formatting mismatch between the datepicker format and either the format returned by JSON or by the use of localStorage.
I’ve tried using ‘stringify’ (L7) and ‘parse’ (L10) to change the date format but that hasn’t had any effect. I’ve also (in desperation) tried changing the perl output to scalar (using ‘qq(#files’) – but again without getting the dates to highlight.
I don’t know what to do to solve the problem and I’d be grateful for any advice that you can offer.
You should transform the data to a valid array, then set it to resultDates and then store the data to the storage.
success: function(res) {
var resultDates = getDataAsArray(res);
localStorage.setItem('dateArray', resultDates);
},
and an small helper function:
function getDataAsArray(data) {
return data.split(",");
}
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.
I am currently running into issues with datepicker automatically converting my time to UTC. Is there anything I can pass into datepicker for it to not give me back a UTC converted string? For example the user picks March 19 on the calendar and the returned string would be something like this
'2014-03-19T04:00:00.000Z'
What I want is ->
'2014-03-19T00:00:00-04:00'
What I am trying now (sort of hacking around it) is trying to use moment js to convert it back to my desired (expected) format, but I am having trouble doing so without hardcoding a subtraction in there. I want to be able to convert it from UTC back to local time.
Does anyone know of a solution to this using moment js or angular?
I ran into the same problem and used a filter that adjusts the date and time using the local data to get around it:
filter('adjustDatepicker', ['$filter', function($filter){
var dateFilter = $filter('date');
return function(dateToFix){
var localDate, localTime, localOffset, adjustedDate;
localDate = new Date(dateToFix);
localTime = localDate.getTime();
localOffset = localDate.getTimezoneOffset() * 60000;
adjustedDate = new Date(localTime + localOffset);
return dateFilter(adjustedDate, 'MM/dd/yyyy');
};
}])
Use it like this in your template file:
{{details.datetomodify | adjustDatepicker}}
I think new Date('2014-03-19T04:00:00.000Z').toString() will give you the local version of the UTC time.