I want to convert string to date in Javascript. I need to do it because I have an array and create table from that. After that I want to use Tablesorter. But it sort it only like textfield. I trying to create new parser. I have string like:
"02 January 2010"
I need to create date type from that. Is it possible in Javascript? I tried
DateFormat format = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
Date date = format.parse(s);
But it doesnt work. How would I do that?
With a standard date format, you can create a date parser that doesn't need to reformat the date (demo)
$(function () {
$.tablesorter.addParser({
id: 'ddMMMMyyyy',
is: function() {
return false;
},
format: function(s) {
var date = new Date(s);
return date instanceof Date && isFinite(date) ? date.getTime() : s;
},
type: 'numeric'
});
$('table').tablesorter({
headers : {
5: { sorter: 'ddMMMMyyyy' }
}
});
});
Related
I'm trying to modify the below code in React Typescript. I want to return the input value in time format like - "Thu Jan 01 2022 13:03:00 GMT-0500 (Eastern Standard Time)" any suggestions how to do it?
Full Code: https://codepen.io/dcode-software/pen/jOwVqGO
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
return `${selects.hour.value}:${selects.minute.value} ${selects.meridiem.value}`;
}
function numberToOption(number) {
const padded = number.toString().padStart(2, "0");
return `<option value="${padded}">${padded}</option>`;
}
activate();
You can create a new Date object and set the hours and minutes on it. From there you get convert it to a string. Like this:
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
const d = new Date();
d.setMinutes(selects.minute.value);
// setHours takes in hours in 24hr format
if (selects.meridiem.value === "pm") {
d.setHours(selects.hour.value + 12);
} else {
d.setHours(selects.hour.value);
}
return d.toString();
}
If you can reach a Date object somehow, its toLocaleString() method can do something like that (the actual parameters are described here.
let date = new Date();
console.log(date.toLocaleString("en-US", {
timeZone: "EST",
dateStyle: 'full',
timeStyle: 'full',
hour12: false // this is because you seem to want a 24-hour format
}));
If you need more, moment.js might be a library to check.
Main question: How to set closest available date?
Hi all, i'm using bootstrap-datetimepicker.
I've disabled some days from calendar and sometimes current date in range.
So it disables successfully but I want to preset default date into the input value, if I use defaultDate: 'moment' it sets current date (which is disabled).
How to set closest available date?
Does exist any lifehack to resolve it?
Or should I make it manually?
This is how it works now:
var $datesDisabled = [];
$.each($dates, function (key, value) {
$datesDisabled.push(moment(value))
});
// PARAMS TO DATETIMEPICKER
var $params = {
locale: 'en',
format: 'DD/MM/YYYY',
disabledDates: $datesDisabled,
};
// CHECK IF CURRENT DATE IS IN DISABLED ARRAY
if ($.inArray(moment().format('MM/DD/YYYY'), $dates) === -1) {
// IF NOT PRESET CURRENT DATE
$params.defaultDate = 'moment';
} else {
// DO NOT PRESET
$params.useCurrent = false;
}
$('.datetimepicker').datetimepicker($params);
According to the library documentation, you're not supposed to use defaultDate: 'moment'. They do mention the following:
Accepts: date, moment, string
But it means you can provide a Date object, a moment() object or a date string. The string "moment" is none of those, so it probably defaults to today.
However, you can configure the defaultDate like this:
// Using a date string
$('#my-date-picker').datetimepicker({
defaultDate: '2016-08-20'
});
// Using a Date object
$('#my-date-picker').datetimepicker({
defaultDate: new Date('2016-08-20')
});
// Using a moment.js object
$('#my-date-picker').datetimepicker({
defaultDate: moment('2016-08-20')
});
But if you want to have the defaultDate the closest date according to your disabled dates, you'll have to calculate it by yourself. For such a functionality you could create a recursive function that recalls itself with the given date minus or plus 1 until it finds one that is not disabled.
For example:
var disabled = [
new Date('2016-01-03'),
new Date('2016-01-04'),
new Date('2016-01-05'),
new Date('2016-01-08')
];
function getClosest(date, disabled, direction) {
if(!containsDate(disabled, date)) {
return date;
} else {
var prev = getClosest(date.clone().add(direction || -1, 'days'), disabled, direction || -1),
next = getClosest(date.clone().add(direction || 1, 'days'), disabled, direction || 1);
if (Math.abs(date.diff(prev, 'days')) > Math.abs(date.diff(next, 'days'))) {
return next;
} else {
return prev;
}
}
}
function containsDate(dates, given) {
return dates.some(function(date) {
return given.isSame(date, 'day');
});
}
console.log(getClosest(moment('2016-01-02'), disabled).toDate());
console.log(getClosest(moment('2016-01-03'), disabled).toDate());
console.log(getClosest(moment('2016-01-04'), disabled).toDate());
console.log(getClosest(moment('2016-01-05'), disabled).toDate());
console.log(getClosest(moment('2016-01-06'), disabled).toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
I try to sort dates like "Di, 29.03.2016" but this doesnt work because the Sorter doesnt have a AddParser for this format.
I know that the numbers should replace like dd/mm/yyyy,
but how should i replace "Di, " ?
Since I can't tell what language you're targeting ("Di" is the abbreviation for December in several languages), I think it might be easiest to use a date library like sugar or datejs to parse those dates for you.
Make sure to set the locale before the following code.
Sugar (demo):
Date.setLocale('es'); // Spanish
$.tablesorter.addParser({
id: 'sugar',
is: function() {
return false;
},
format: function(s) {
var date = Date.create ? Date.create(s) : s ? new Date(s) : s;
return date instanceof Date && isFinite(date) ? date.getTime() : s;
},
type: 'numeric'
});
DateJS (demo):
// make sure to load the desired locale file
// full list: https://github.com/datejs/Datejs/tree/master/build
$.tablesorter.addParser({
id: 'datejs',
is: function() {
return false;
},
format: function(s) {
var date = Date.parse ? Date.parse(s) : s ? new Date(s) : s;
return date instanceof Date && isFinite(date) ? date.getTime() : s;
},
type: 'numeric'
});
Note: The above two demos are using my fork of tablesorter & copied from this file, but these parsers will work in the original tablesorter (v2.0.5).
Note 2: There is also a parser for jQuery Globalize (demo), but it is a bit more complicated to set up and use, so I didn't include it here; and the globalize parser may not work properly with the original version of tablesorter.
I am working with ExtJS and want to use Ext.Date.format(value,format). I have date as 2014/03/05. How can I convert this to the date object so that it can be passed as 'value' argument to the format() function?
You can try this :
var dt = new Date('2014/03/05');
And you do this to format your date Ext.Date.format(dt,'d-m-Y'); or whatever format you want. :)
You can parses date:
var dt = Ext.Date.parse("2014/03/05", "Y/m/d");
Then you can format it another format:
var td = Ext.Date.format(dt,'d-m-Y');
I've been using tablesorter a lot in my website like this
$(".tablesorter").tablesorter({
widgets: ['zebra'],
dateFormat: 'uk',
});
But i've a problem with date in the format : MM/YYYY (it's when I don't have the day I prefer showing 12/2005 than 00/12/2005).
This format does not work with tablesorter dateFormat uk. How to make it working ?
And the difficulty is that I can have in the same table differents formats like this :
Date - Title
11/2005 - Movie 1
12/11/2005 - Movie 2
2006 - Movie 3
Thank you.
You could add a custom parser:
$.tablesorter.addParser({
id: 'rough-date',
is: function() {
// return false so this parser is not auto detected
return false;
},
format: function(s) {
// format to look like an ISO 8601 date (2005-11-12).
// Month-only dates will be formatted 2005-11.
return s.split('/').reverse().join('-');
},
type: 'text' // sort as strings
});
And then use it like this (where 0 is the column number that contains the date):
$(".tablesorter").tablesorter({
headers: {
0: {
sorter:'rough-date'
}
}
});
Here's a JSFiddle.