Date String sorting in trNgGrid - javascript

My column contains a list of dates in string format. Eg.: "Aug 2013", "Sep 2012" etc
But when I try to sort, it sorts alphabetically. One approach I thought of was to convert it to epoch format by using javascript.
new Date("Aug 2013").getTime()
This returns a long value in epoch format 1375295400000 and I believe I can sort it then.
I have trouble integrating it in the frontend code. Is there any way I can achieve this?

To sort your list of dates (in string format), you can use the sort function with a custom comparison function. This comparison function converts the two strings to date objects then to millisecond and returns the difference.
var list = ["Aug 2013", "Sep 2012", "Sep 2010"];
var sli = list.sort(function (a, b) {
var d1 = new Date(a).getTime();
var d2 = new Date(b).getTime();
return d1 - d2;
});
res.end('sli='+sli);
Output:
sli=Sep 2010,Sep 2012,Aug 2013

Alright the fix was pretty simple. I passed the UTC time format in JSON data as utcTime. Hence in the TrNgGrid column declaration
field-name="utcTime" display-format="displayTimePeriod:gridItem"
And in the angular module define displayTimePeriod filter as
.filter("displayTimePeriod", function() {
return function(fieldValueUnused, item) {
return item.timePeriod;
}
})
So sorting happens based on utcTime variable but in the view I have timePeriod displayed.

Related

How to format a date received from my server using javascript?

I need to format a date with javascript but I'm having a little trouble solving this.
I get two dates, I need to format them and then join the values.
On one of the dates I get this:
"2022-07-12T04:00:00-0300"
And on the other date I get this:
"2022-07-12T06:00:00-0300"
These are always dynamic dates returned from my backend, but here on the frontend I need to display these two dates in this following format:
"04:00 - 06:00"
This is assuming you only need the hours and minutes.
function datesToRange(start, end) {
if (!start || !end) return ""; // If either date is null or undefined.
return start.substring(12, 17) + " - " + end.substring(12, 17);
}
Now you can call this method to get the range in your required format.
E.g.
datesToRange("2022-07-12T04:00:00-0300", "2022-07-12T06:00:00-0300");
Will return "04:00 - 06:00".
You can use slice() method.
var date1 = "2022-07-12T04:00:00-0300";
var date2 = "2022-07-12T06:00:00-0300";
var formatted = `${date1.slice(11, 16)} - ${date2.slice(11, 16)}`;
console.log(formatted);

How to format a Date in a Specific Format in React.js?

I want to show the full date formatted from this 2020-11-09T17:50:00.000Z
to this 22/1/2020 14:20:22 format. I know how get the desired format via moment.js, but want to achieve this with JavaScript Date.
Here is what I have now, but this is not what I want.
let d = new Date("2020-11-09T17:50:00.000Z".toLocaleString("en-US"))
console.log(d);
Any help will be appreciated
You can always do it manually, the Date API only has a limited set of functions like .toLocaleDateString() which will give you "11/9/2020" and .toGMTString() will return "Mon, 09 Nov 2020 17:50:00 GMT".
Using your Date APIs, you can build the string yourself using what you have.
var timeString = d.toGMTString().split(" ")[4]; //This will return your 17:50:00
//For the date string part of it
var dateNumber = d.getDate();
var monthNumber = d.getMonth() + 1;
var yearNumber = d.getFullYear();
var dateString = `${dateNumber}/${monthNumber}/${yearNumber}`;
var finalDateString = [dateString, timeString].join(" ");
toLocaleString() can produce many formats, and you can choose the locale to get the format (or close to it) that you want.
The locale "en-GB" gives you almost what you want; you just need to remove the comma that it puts in...
let d = new Date(2020, 0, 22, 14, 20, 22);
let output = d.toLocaleString("en-GB")
.replace(',' ,'');
console.log(output);
You can actually control the output further by using the options parameter.
But also see the Intl object for its DateTimeFormat constructor.

How to JSON stringify a javascript Date and preserve timezone

I have a date object that's created by the user, with the timezone filled in by the browser, like so:
var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)
When I stringify it, though, the timezone goes bye-bye
JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"
The best way I can get a ISO8601 string while preserving the browser's timezone is by using moment.js and using moment.format(), but of course that won't work if I'm serializing a whole command via something that uses JSON.stringify internally (in this case, AngularJS)
var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);
For completeness, my domain does need both the local time and the offset.
Assuming you have some kind of object that contains a Date:
var o = { d : new Date() };
You can override the toJSON function of the Date prototype. Here I use moment.js to create a moment object from the date, then use moment's format function without parameters, which emits the ISO8601 extended format including the offset.
Date.prototype.toJSON = function(){ return moment(this).format(); }
Now when you serialize the object, it will use the date format you asked for:
var json = JSON.stringify(o); // '{"d":"2015-06-28T13:51:13-07:00"}'
Of course, that will affect all Date objects. If you want to change the behavior of only the specific date object, you can override just that particular object's toJSON function, like this:
o.d.toJSON = function(){ return moment(this).format(); }
I'd always be inclined to not mess with functions in the prototype of system objects like the date, you never know when that's going to bite you in some unexpected way later on in your code.
Instead, the JSON.stringify method accepts a "replacer" function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) which you can supply, allowing you to override the innards of how JSON.stringify performs its "stringification"; so you could do something like this;
var replacer = function(key, value) {
if (this[key] instanceof Date) {
return this[key].toUTCString();
}
return value;
}
console.log(JSON.stringify(new Date(), replacer));
console.log(JSON.stringify({ myProperty: new Date()}, replacer));
console.log(JSON.stringify({ myProperty: new Date(), notADate: "I'm really not", trueOrFalse: true}, replacer));
Based on Matt Johnsons 's answer, I re-implemented toJSON without having to depend on moment (which I think is a splendid library, but a dependency in such a low level method like toJSON bothers me).
Date.prototype.toJSON = function () {
var timezoneOffsetInHours = -(this.getTimezoneOffset() / 60); //UTC minus local time
var sign = timezoneOffsetInHours >= 0 ? '+' : '-';
var leadingZero = (Math.abs(timezoneOffsetInHours) < 10) ? '0' : '';
//It's a bit unfortunate that we need to construct a new Date instance
//(we don't want _this_ Date instance to be modified)
var correctedDate = new Date(this.getFullYear(), this.getMonth(),
this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(),
this.getMilliseconds());
correctedDate.setHours(this.getHours() + timezoneOffsetInHours);
var iso = correctedDate.toISOString().replace('Z', '');
return iso + sign + leadingZero + Math.abs(timezoneOffsetInHours).toString() + ':00';
}
The setHours method will adjust other parts of the date object when the provided value would "overflow". From MDN:
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly. For example, if you use 100 for secondsValue, the minutes will be incremented by 1 (minutesValue + 1), and 40 will be used for seconds.
When I stringify it, though, the timezone goes bye-bye
That’s because Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time) is actually the result of the toString method of the Date object, whereas stringify seems to call the toISOString method instead.
So if the toString format is what you want, then simply stringify that:
JSON.stringify(date.toString());
Or, since you want to stringify your “command” later on, put that value in there in the first place:
var command = { time: date.toString(), contents: 'foo' };
If you have a JS Date Object and want to stringify it to preserve the timezone, then you should definitely use toLocaleDateString().
It is a very powerful helper function that can help you format your Date object in every way possible.
For example, if you want to print "Friday, February 1, 2019, Pacific Standard Time",
const formatDate = (dateObject : Date) => {
const options: any = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZoneName: 'long'
};
return dateObject.toLocaleDateString('en-CA', options);
};
Thus, by modifying the options object, you can achieve different styles of formatting for your Date Object.
For more information regarding the ways of formatting, refer to this Medium article: https://medium.com/swlh/use-tolocaledatestring-to-format-javascript-dates-2959108ea020
let date = new Date(JSON.parse(JSON.stringify(new Date(2011, 05, 07, 04, 0, 0))));
I've created a small library that preserves the timezone with ISO8601 string after JSON.stringify. The library lets you easily alter the behavior of the native Date.prototype.toJSON method.
npm: https://www.npmjs.com/package/lbdate
Example:
lbDate().init();
const myObj = {
date: new Date(),
};
const myStringObj = JSON.stringify(myObj);
console.log(myStringObj);
// {"date":"2020-04-01T03:00:00.000+03:00"}
The library also gives you options to customize the serialization result if necessary.

Converting a string into a date

I have the following script which joins 2 feeds and displays them on the screen
$.when( //get feed 1, //get feed 2 ).done(function(a1, a2){
var data = a1[0]response.Data.feed.entries.concat(a2[0].responseData.feed.entries);
var sorted = data.sort(function(a, b) {
if(a.publishedDate > b.publishedDate) {
return 1
}
if(a.publishedDate < b.publishedDate) {
return -1
}
return 0
});
for( i = o; i <= sorted.length - 1; i++ ) {
document.write(sorted[i].title);
document.write(sorted[i].publishedDate);
}
});
This returns all the rows, but it doesn't sort the rows. The sorting seems completely random. I'm assuming it's because the dates are formatted as follows in the JSON data:
Mon, 23 Sep 2013 04:37:45 -0700
What does that -0700 mean
How do I convert that date string into a proper date object so I can sort the results correctly?
-0700 means the UTC offset UTC-07:00.
I'm strongly recommend you to use Moment.js library to deal with date and time, formatting and conversions to make your "Date & Time JavaScript Life" easy and funny.
As Alnitak said this particular format is accepted by Date.parse therefore if you use one of accepted formats you can just use native JavaScript for sorting.
var dateStrings,
sortDates;
dateStrings = [
'Mon, 23 Sep 2013 04:37:45 -0700',
'Sun, 22 Sep 2013 05:27:32 +0300',
'Mon, 23 Sep 2013 03:14:17 -0700'
];
sortDates = function(dateStrings) {
return dateStrings.sort(function(a, b) {
return new Date(a) - new Date(b);
});
};
console.log(sortDates(dateStrings));
Fiddle
The variable sorted in your code snippet could be properly retrieved in this way:
var sorted = data.sort(function(a, b) {
return new Date(a.publishedDate) - new Date(b.publishedDate);
});
Well, -0700 means.. is 7 hours earlier than Greenwich Mean ...yor can check more in wikipedia
And if you want to convert any date properly, i strongly recommend you to use the library DateJS (http://www.datejs.com/)
You can use syntatic sugarr..!! to create your object...
Date.parse('Thu, 1 July 2013 20:20:20');
voila.. its very easy...
You can pass the string to new Date(...) to convert to a real Date object.
To sort however you also need to pass a specific sort function because default Javascript sort on arrays just converts elements to string and compares the result of conversion (thus any "Mon"day will happen to be placed before any "Sun"day).
Something that should work is
dates.sort(function(a, b){ return a - b; });

Validate two dates of this "dd-MMM-yyyy" format in javascript

I have two dates 18-Aug-2010 and 19-Aug-2010 of this format. How to find whether which date is greater?
You will need to create a custom parsing function to handle the format you want, and get date objects to compare, for example:
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
customParse("18-Aug-2010");
// "Wed Aug 18 2010 00:00:00"
customParse("19-Aug-2010") > customParse("18-Aug-2010");
// true
You can do the parsing manually, for your given format, but I'd suggest you use the date.js library to parse the dates to Date objects and then compare.
Check it out, its awesome!
And moreover, its a great addition to your js utility toolbox.
The native Date can parse "MMM+ dd yyyy", which gives:
function parseDMY(s){
return new Date(s.replace(/^(\d+)\W+(\w+)\W+/, '$2 $1 '));
}
+parseDMY('19-August-2010') == +new Date(2010, 7, 19) // true
parseDMY('18-Aug-2010') < parseDMY('19-Aug-2010') // true
Firstly, the 'dd-MMM-yyyy' format isn't an accepted input format of the Date constructor (it returns an "invalid date" object) so we need to parse this ourselves. Let's write a function to return a Date object from a string in this format.
function parseMyDate(s) {
var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var match = s.match(/(\d+)-([^.]+)-(\d+)/);
var date = match[1];
var monthText = match[2];
var year = match[3];
var month = m.indexOf(monthText.toLowerCase());
return new Date(year, month, date);
}
Date objects implicitly typecast to a number (milliseconds since 1970; epoch time) so you can compare using normal comparison operators:
if (parseMyDate(date1) > parseMyDate(date2)) ...
Update: IE10, FX30 (and likely more) will understand "18 Aug 2010" without the dashes - Chrome handles either
so Date.parse("18-Aug-2010".replace("/-/g," ")) works in these browsers (and more)
Live Demo
Hence
function compareDates(str1,str2) {
var d1 = Date.parse(str1.replace("/-/g," ")),
d2 = Date.parse(str2.replace("/-/g," "));
return d1<d2;
}

Categories

Resources