Datatable Date format is not working correctly - date

My date is showing in datatable in this format : "2013-09-02 12:00:00 AM".
I want it in this format: "2013/09/02".
I've googled and found a way to do so. But the code is not working. Output is showing "NaN/NaN/NaN".
My script for datatable is here:
$(document).ready(function () {
$('#RequisitionTbl').dataTable({
"aoColumnDefs": [
{
"aTargets": [0],
"sType": 'date',
"fnRender": function (oObj) { // trying to format(like "2013/09/02") the date here
var javascriptDate = new Date(oObj.aData[0]);
javascriptDate = javascriptDate.getDate() + "/" + javascriptDate.getMonth() + "/" + javascriptDate.getFullYear();
return "<div class= date>" + javascriptDate + "<div>";
}
},
{ "sWidth": "350px", "aTargets": [0] },
{ "sWidth": "180px", "aTargets": [1] },
{ "sWidth": "200px", "aTargets": [2] },
{ "bSortable": false, "aTargets": [4] },
{ "bSearchable": false, "aTargets": [4] }
],
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "Display _MENU_ records"
}
}).columnFilter({
sPlaceHolder: "head:before",
aoColumns: [
{ type: 'date-range' }, ,{},]
});
});
Need help to fin out the problem.

Remember that Month is zero-based index:
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var javascriptDate = year + '/' + month + '/' + day // Modify as you need
Hope this helps!

Related

Enable Particular Date in datepicker

I have disabled all Mondays in datepicker but on some dates I have to enable that particular date on Monday, so how can I do that? I have pasted the code :
const datepicker2 = new Datepicker(elem2, {
daysOfWeekDisabled: dates_diable,
beforeShowDay: function(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
console.log(dmy+' : '+($.inArray(dmy, availableDates)));
if ($.inArray(dmy, availableDates) > '-1') {
//console.log('yes');
return true;
}
},
format: 'dd/mm/yyyy',
buttonClass: 'btn',
minDate:"Today",
maxDate:maxDate,
datesDisabled: [],
todayHighlight: false,
});

Customize tcomb-form-native's data filds

I'm trying to customize the Data field of atcomb-form-native module.
I wish the date fields were a classic input field but I still tried different methods, I didn't succeed.
I tried to override the datepicker field style but put the style when opening the picker to insert the date and not around the message.
Instead of 'Tap here to select a date' I would like to insert a phrase at will. How can I do?
Also, how can I customize the date format? I tried following this issue of github but it didn't solve the problem.
This is the part of code for formatting the data:
config: {
format: date => {
let toBeFormatted = new Date(date);
return String('Valida dal' + toBeFormatted.format('DD/MM/YYYY'));
},
dateFormat: date => {
let toBeFormatted = new Date(date);
return String('Valida dal' + toBeFormatted.format('DD/MM/YYYY'));
},
timeFormat: date => {
let toBeFormatted = new Date(date);
return String('Valida dal' + toBeFormatted.format('DD/MM/YYYY'));
},
}
Okay. I can give you my code. I had a little trouble finding it, but finally, everything is in the tcomb documentation.
The two important points to answer your question are :
"defaultValueText" and "format: (date) => ..."
import React, { Component } from "react";
import Expo from "expo";
import t from "tcomb-form-native";
import moment from 'moment';
import { StyleSheet, Text, Date} from "react-native";
import { Button } from "react-native-elements";
const Form = t.form.Form;
Form.stylesheet.dateValue.normal.borderColor = '#d0d2d3';
Form.stylesheet.dateValue.normal.backgroundColor = '#ffffff';
Form.stylesheet.dateValue.normal.borderRadius= 5,
Form.stylesheet.dateValue.normal.color = 'grey';
Form.stylesheet.dateValue.normal.borderWidth = 1;
const User = t.struct({
pseudo: t.String,
birthday: t.Date,
});
const options = {
order: ['pseudo','birthday'],
fields: {
pseudo: {
placeholder: 'Enter Name',
error: 'Name is empty?',
},
birthday: {
mode: 'date',
label: 'birthday',
config: {
defaultValueText: 'Enter birthday', // Allows you to format the PlaceHolders !!
format: (date) => {
return moment(date).format('DD-MM-YYYY'); // Allows you to format the date !!
},
}
},
},
};
... ...
export default class SignUp extends Component {
state = {...
render() {
return (
<View style={styles.container}>
<Form
type={User}
ref={c => (this._form = c)} // assign a ref
options={options} //set form options
/>
<Button
title="Sign Up!"
buttonStyle={styles.button}
onPress={this.handleSubmit}
/>
</View>
);
}
}
} ...

Repeating values on x-axis Morris.js line chart

I'm trying to display line chart with daily stats. But the dates on X- axis seem to be repeating.
Link to image
Here is the code for line chart:
new Morris.Line({
element: 'chart',
data: [ #foreach($Data as $data)
{ date: '{{$data['date']}}', value: {{$data['diff']}}},
#endforeach
],
xkey: ['date'],
xLabelFormat: function(date) {
return date.getFullYear() + '/' + (date.getMonth()+1)+ '/' + date.getDate();
},
xLabelAngle : 50,
ykeys: ['value'],
labels: ['Value'],
resize: true,
smooth: true,
lineColors: ['#9ec628'],
dateFormat: function(date) {
date = new Date(date);
return date.getFullYear()+ '/' + (date.getMonth()+1)+ '/' + date.getDate();
},
});
I also tried parseTime: false but that's not helping.
The solution is to add the option xLabels: 'day' to your config, then only 1 value in x-axis per day would be displayed. I found that option in the documentation http://morrisjs.github.io/morris.js/lines.html

How to add comma in stacked column highchart in indian format?

I am using stacked column highchart. I am getting few value in column and tooltip. Now I want to show this value in Indian format with comma separator. Suppose I have a value like 123456789.So I want to show this value in 12,34,56,789 format. How can I do this? Please share with me if any body has any idea.
I tried this below code.
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
But It gives 123,456,789 format, I want something like 12,34,56,789. The Indian format.
My codes are below:
function draw_charts(amount, interest , year)
{
/*Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});*/
$('#chart_area').highcharts({
chart: {
type: 'column',
backgroundColor: 'transparent'
},
title: {
text: 'Year wise break-up'
},
xAxis: {
categories: year,
title: {
text: 'Year'
}
},
yAxis: {
min: 0,
title: {
text: 'Amount'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: -5,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}
}
},
series: [{
name: 'Interest',
data: interest, color: '#7fb801'
},{
name: 'Principal',
data: amount, color: '#4fc1e9'
}],
exporting: { enabled: false },
credits: { enabled: false },
});
}
You can slightly modify the numberFormat function, changing from the lines (from source):
thousands = strinteger.length > 3 ? strinteger.length % 3 : 0;
// ...
ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep);
To these lines:
thousands = strinteger.length > 3 ? (strinteger.length - 1) % 2 : 0;
// ...
ret += strinteger.substr(thousands).replace(/(\d{2})(?=\d{3})/g, '$1' + thousandsSep);
Ending up with this function:
Highcharts.numberFormat = function (number, decimals, decimalPoint, thousandsSep) {
number = +number || 0;
decimals = +decimals;
var lang = Highcharts.getOptions().lang,
origDec = (number.toString().split('.')[1] || '').length,
decimalComponent,
strinteger,
thousands,
absNumber = Math.abs(number),
ret;
if (decimals === -1) {
decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793).
} else if (!isNumber(decimals)) {
decimals = 2;
}
// A string containing the positive integer component of the number
strinteger = String(Highcharts.pInt(absNumber.toFixed(decimals)));
// Leftover after grouping into thousands. Can be 0, 1 or 3.
thousands = strinteger.length > 3 ? (strinteger.length - 1) % 2 : 0;
// Language
decimalPoint = Highcharts.pick(decimalPoint, lang.decimalPoint);
thousandsSep = Highcharts.pick(thousandsSep, lang.thousandsSep);
// Start building the return
ret = number < 0 ? '-' : '';
// Add the leftover after grouping into thousands. For example, in the number 42 000 000,
// this line adds 42.
ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : '';
// Add the remaining thousands groups, joined by the thousands separator
ret += strinteger.substr(thousands).replace(/(\d{2})(?=\d{3})/g, '$1' + thousandsSep);
// Add the decimal point and the decimal component
if (decimals) {
// Get the decimal component, and add power to avoid rounding errors with float numbers (#4573)
decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1));
ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2);
}
return ret;
};
I've prefixed some function calls with Highcharts to make it work without a custom js-file.
See this JSFiddle demonstration of it in use.

Count days between two dates excluding weekends

How can I find the difference between two dates in DB2 (excluding weekends)?
Are there any functions that will do this in DB2? Or do I need to write a query myself?
There is AFAIK no such function. It is however easy to write a query that calculates this:
with cal(d) as (
values date('2015-01-01') -- start_date
union all
select d + 1 day from cal
where d < '2015-01-15' -- end_date
) select count(case when dayofweek(d) between 2 and 6 then 1 end)
from cal;
If you do a lot of these kind of calculations you might want to create a calendar table, you can add attributes like national holiday etc to this table.
you can use this function:
DAYOFWEEK(CURRENT_DATE)
The following calculation will return the number of working days between two dates:
[Week(End Date) - Week(Start Date)] * 5 + [DayofWeek(Start Date) - DayofWeek(End Date)]
This will only work if the functions for Week and Day or equivalent are native to the database driver. Client Access and Sybase native connection both support these functions.
The Week function will give the integer value of the week of the year selected. The DayofWeek will give an Integer value from 1-7 for the day selected.
IBM Support Working Days Between Two Dates
This is the best way to implement difference between two dates excluding weekend means Saturday and Sunday and also excluding national holiday....
/******
* First, we'll extend the date object with some functionality.
* We'll add an .each() function, as well as an .adjust() function.
* .each() will give us the ability to loop between two dates, whether
* by 'day', 'week' or 'month'.
* .adjust() will allow us to move a given day by a given unit. This is used
* like so: currentDate.adjust('days', 1) to increment by one day.
******/
Date.prototype.each = function(endDate, part, step, fn, bind){
var fromDate = new Date(this.getTime()),
toDate = new Date(endDate.getTime()),
pm = fromDate <= toDate? 1:-1,
i = 0;
while( (pm === 1 && fromDate <= toDate) || (pm === -1 && fromDate >= toDate) ){
if(fn.call(bind, fromDate, i, this) === false) break;
i += step;
fromDate.adjust(part, step*pm);
}
return this;
};
Date.prototype.adjust = function(part, amount){
part = part.toLowerCase();
var map = {
years: 'FullYear', months: 'Month', weeks: 'Hours', days: 'Hours', hours: 'Hours',
minutes: 'Minutes', seconds: 'Seconds', milliseconds: 'Milliseconds',
utcyears: 'UTCFullYear', utcmonths: 'UTCMonth', weeks: 'UTCHours', utcdays: 'UTCHours',
utchours: 'UTCHours', utcminutes: 'UTCMinutes', utcseconds: 'UTCSeconds', utcmilliseconds: 'UTCMilliseconds'
},
mapPart = map[part];
if(part == 'weeks' || part == 'utcweeks')
amount *= 168;
if(part == 'days' || part == 'utcdays')
amount *= 24;
this['set'+ mapPart]( this['get'+ mapPart]() + amount );
return this;
}
/*******
* An array of national holidays. This is used to test for the exclusion of given
* days. While this list is national days, you could tailor it to regional, state
* or given religious observances. Whatever.
******/
natDays = [
{
month: 1,
date: 26,
type: "national - us",
name: "New Year's Day"
},
{
month: 1,
date: 21,
type: "national - us",
name: "Martin Luther King Day"
},
{
month: 2,
date: 18,
type: "national - us",
name: "President's Day (Washington's Birthday"
},
{
month: 5,
date: 27,
type: "national - us",
name: "Memorial Day"
},
{
month: 7,
date: 4,
type: "national - us",
name: "Independence Day"
},
{
month: 9,
date: 2,
type: "national - us",
name: "Labor Day"
},
{
month: 10,
date: 14,
type: "national - us",
name: "Columbus Day"
},
{
month: 11,
date: 11,
type: "national - us",
name: "Veteran's Day"
},
{
month: 11,
date: 29,
type: "national - us",
name: "Thanksgiving Day"
},
{
month: 12,
date: 25,
type: "national - us",
name: "Christmas Day"
}
];
/******
* This uses the national holidays array we just set, and checks a given day to see
* if it's in the list. If so, it returns true and the name of the holiday, if not
* it returns false.
*****/
function nationalDay(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == (natDays[i].month-1)
&& date.getDate() == natDays[i].date) {
return [true, natDays[i].name];
}
}
return [false, null];
}
/******
* This function takes two dates, as start and end date, and iterates through the
* dates between them. For each date, it checks if the current date is a week day.
* If it is, it then checks if it isn't a holiday. In this case, it increments
* the business day counter.
******/
function calcBusinessDays(startDate, endDate) {
// input given as Date objects
var iDateDiff=0, holidays = [];
startDate.each(endDate, 'days', 1, function(currentDate, currentStep, thisDate){
if(currentDate.getDay() != 0 && currentDate.getDay() != 6 ) {
var isAHoliday = nationalDay(currentDate);
if(!isAHoliday[0]){
iDateDiff += 1;
} else {
holidays.push(isAHoliday[1]);
}
}
});
return {count: iDateDiff, holidays: holidays};
};
$(function(){
var results, exclusions;
$( "#startDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#endDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#endDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$("#calculateMe").on("click", function(){
var startDate = new Date($("#startDate").val()),
endDate = new Date($("#endDate").val() );
// Calculate the number of business days. This returns an object, with
// two members: count and holidays
results = calcBusinessDays(startDate, endDate);
exclusions = "Excluded weekends";
if (results.holidays.length > 0) {
// We have holidays, tell the user about them...
exclusions += " and the following holidays: ";
for(var i=0; i<results.holidays.length; i += 1){
exclusions += results.holidays[i]+", ";
}
} else {
// No holidays.
exclusions += ".";
}
$("#result").text(results.count + " business days." ).append("<p>("+exclusions+")</p>");
});
});
<div id="content">
<input type="text" class="myDateClass" id="startDate"/>
<input type="text" class="myDateClass" id="endDate"/>
<button id="calculateMe">How many business days?</button>
<div id="result"></div>
</div>
Fiddle