How can I get the current date, current year, current month, and current week in sapui5? This is the code I started with:
var oType = new sap.ui.model.type.Date();
oType = new sap.ui.model.type.Date({ source: {}, pattern: "MM/dd/yyyy" });
I have no idea where to go from here. Any help would be greatly appreciated.
EDIT: How do I get the following javascript function into a sapui5 table?
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function dateFunction() {
var today = new Date();
var dd = addZero(today.getDate());
var MM = addZero(today.getMonth() + 1);
var yyyy = today.getFullYear();
var hours = addZero(today.getHours());
var min = addZero(today.getMinutes());
var sec = addZero(today.getSeconds());
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
today = MM + '/' + dd + '/' + yyyy + " " + hours + ":" + min + ":" + sec + " " + ampm;
}
To get Current Date:
there is NO predefined function in SAPUI5, hence use native JavaScript Method:
var oDate = new Date();
How to put date in a table?
JS Fiddle
var oData = {
results: [{
name: "Today",
date: new Date()
}, {
name: "Someday",
date: new Date("2015/01/01")
}, {
name: "New Year",
date: new Date("2016/01/01")
}]
}
var oModel = new sap.ui.model.json.JSONModel(oData);
// create table:
var oTable = new sap.m.Table({
columns: [
new sap.m.Column({
header: new sap.m.Label({
text: "When"
})
}),
new sap.m.Column({
header: new sap.m.Label({
text: "Date"
})
})]
});
var oType = new sap.ui.model.type.Date({
pattern: "MM/dd/yyyy"
});
var oTemplate = new sap.m.ColumnListItem({
cells: [
new sap.m.Text({
text: "{name}"
}),
new sap.m.Text({
text: {
path: 'date',
type: oType
}
})]
});
oTable.setModel(oModel);
oTable.bindItems("/results", oTemplate);
oTable.placeAt("content");
Update: Based on comment request
All you need is this:
var oType = new sap.ui.model.type.Date({
pattern: "MM/dd/yyyy"
});
oTable.addColumn(new sap.ui.table.Column("today", {
label: new sap.m.Label({
text: {
path: 'today',
type: oType
}
})
sortProperty: 'today',
filterProperty: 'today'
}));
Related
How to set auto select +7 days. User set first value e.g. 22.02.2022 and datapicker marks 01.03.2022 it means that endDate must be startDate +7
$('input[name="daterange"]').daterangepicker(
{
dateFormat: "MMMM D, YYYY",
timePicker: true,
startDate: moment(),
endDate: moment().startOf("days").add(7, "days"),
opens: "left",
applyButtonClasses: "Search",
},
var startDate = $("#datarange").data("daterangepicker").startDate._d;
var startDate_iso = startDate.toISOString();
if (
startDate_iso.substring(0, 10) == new Date().toISOString().substring(0, 10)
) {
//[wyl] dateCurrent = new Date();
//[wyl] interval_do = dateCurrent.toISOString();
var startDate = $("#datarange").data("daterangepicker").startDate._d;
var startDate_iso = startDate.toISOString();
var endDate = $("#datarange").data("daterangepicker").endDate._d;
var endDate_iso = endDate.toISOString();
interval = startDate_iso + "/" + endDate_iso;
console.log("A new date was set: " + startDate_iso + " to " + endDate_iso);
}
else {
var startDate = $("#datarange").data("daterangepicker").startDate._d;
var startDate_iso = startDate.toISOString();
var endDate = $("#datarange").data("daterangepicker").endDate._d;
var endDate_iso = endDate.toISOString();
interval = startDate_iso + "/" + endDate_iso;
console.log("A new date was set: " + startDate_iso + " to " + endDate_iso);
console.log("==================== Select date ================");
}
I have tried min / max but this is not the expected solution. it just allows me to return a date from the default to +7 days.
Thank you very much for any help.
I am trying to implement this jQuery Calendar into my website. I've got the calendar running, and everything works.
I want to be able to alter the date in the calendar when a user pushes one of four buttons:
1 hour
Tomorrow
1 week
2 weeks
When a user pushes a button I would like the calendar to change the date accordingly. The calendar has the option called startDate that I can use for the purpose - but I can't seem to trigger it.
The content of val = f.x. 2020-03-07 10:02
$.datetimepicker.setLocale('da');
$('#datetimepicker').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date(document.getElementById('timeForAlert').value),
onSelectDate: function() {
userHasChosen();
},
onSelectTime: function() {
userHasChosen();
}
});
$('#datetimepicker4').datetimepicker({
format: 'Y-d-m'
});
$('.some_class').datetimepicker();
function makeReadable(val) {
var mydate = new Date(val);
var hour = document.getElementById('hour').value;
var minute = document.getElementById('minutes').value;
var str = mydate.getFullYear() + '-' + ("0" + (mydate.getMonth() + 1)).slice(-2) + '-' + ("0" + mydate.getDate()).slice(-2) + ' ' + hour + ':' + minute + ':00';
return str;
}
function oneday(val) {
document.getElementById('datetimepicker').value = val;
document.getElementById('timeForAlert').value = makeReadable(val);
$.datetimepicker();
stopReload();
}
Found the solution asking in another forum.
The documentation for this script is terrible !
Here is what we found:
$(function() {
$('#dt').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date()
});
});
$('#btn').click(function() {
$('#dt').datetimepicker({
value: new Date('2020-01-01T00:00:00Z')
});
});
Run this from a button with id = btn and you're set
I'm creating a Google TimeLine chart, which works well except for the fact that when there's no data to return a broken text is shown inside the chart area, which should just remain blank.
I already checked if it was some wrong return from my DB (I commented all the DB access code to ensure the list that fills the chart would return empty) and the error persist.
So my best shot is that the error is with some misconfiguration of the Google timeline chart area itself.
This is the code that works perfectly when there is data return:
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChartTimeLine);
function reloadChartTimeLine(){
var inidate=document.getElementById("inidate").value;
var enddate=document.getElementById("enddate").value;
var idRack=document.getElementById("idRack").value;
jQuery.ajax({
type: "POST",
url: '<c:url value="/tracking/searchRackTimeLineByDate" />',
data: { idRack: idRack, inidate: inidate, enddate:enddate },
success: function(data) { drawChartTimeLine(data);}
});
}
function drawChartTimeLine(response) {
var data = new google.visualization.DataTable();
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
data.addColumn( 'string','Local' );
data.addColumn( 'string','Situação' );
data.addColumn( 'date', 'Início' );
data.addColumn( 'date', 'Fim' );
if(response!=undefined){
response.forEach(function (row) {
data.addRow([
row.local,
row.movementStatus,
new Date(row.startDate),
new Date(row.endDate)
]);
});
}
data.insertColumn(2, {type: 'string', role: 'tooltip', p: {html: true}});
var dateFormat = new google.visualization.DateFormat({
pattern: 'd/M/yy HH:mm:ss'
});
var options = {
tooltip: {isHtml: true},
hAxis:{format:"dd/M" },
timeline: { showBarLabels: false},
colors: ['#0f434c','#a30404'],
};
var ticks = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticks.push(data.getValue(i, 0));
var duration = (data.getValue(i, 4).getTime() - data.getValue(i, 3).getTime()) / 1000;
var days = parseInt( duration / 86400 )
var hours = parseInt( duration / 3600 ) % 24;
var minutes = parseInt( duration / 60 ) % 60;
var seconds = duration % 60;
var tooltip = '<div class="ggl-tooltip"><span>' +
data.getValue(i, 1) + '</span></div><div class="ggl-tooltip"><span>' +
data.getValue(i, 0) + '</span>: ' +
dateFormat.formatValue(data.getValue(i, 3)) + ' - ' +
dateFormat.formatValue(data.getValue(i, 4)) + '</div>' +
'<div class="ggl-tooltip"><span>Duração : </span>' +
days + 'd '+hours + 'h ' + minutes + 'm ' + seconds + 's ';
data.setValue(i, 2, tooltip);
}
options["hAxis"]["ticks"] = [0]
chart.draw(data, options);
}
Here's a screenshot to the issue (there's no data to be returned in the selected period);
https://imgur.com/yKN9j9j
I selected and pasted the broken text and it goes "31/12" although in the chart canvas only a broken "/12" is visible. This same text occurs for every empty period.
A little late but I managed to show the chart without the canvas area when there's nothing to return just adding a lenght condition to use the response from ajax and putting all the code inside this condition as shown below; thanks for all the tips:
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChartTimeLine);
function reloadChartTimeLine(){
var inidate=document.getElementById("inidate").value;
var enddate=document.getElementById("enddate").value;
var idRack=document.getElementById("idRack").value;
jQuery.ajax({
type: "POST",
url: '<c:url value="/tracking/searchRackTimeLineByDate" />',
data: { idRack: idRack, inidate: inidate, enddate:enddate },
success: function(data) { drawChartTimeLine(data);}
});
}
function drawChartTimeLine(response) {
var data = new google.visualization.DataTable();
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
data.addColumn( 'string','Local' );
data.addColumn( 'string','Situação' );
data.addColumn( 'date', 'Início' );
data.addColumn( 'date', 'Fim' );
if(response!=undefined && response.length>0){
response.forEach(function (row) {
data.addRow([
row.local,
row.movementStatus,
new Date(row.startDate),
new Date(row.endDate)
]);
});
data.insertColumn(2, {type: 'string', role: 'tooltip', p: {html: true}});
var dateFormat = new google.visualization.DateFormat({
pattern: 'd/M/yy HH:mm:ss'
});
var options = {
tooltip: {isHtml: true},
hAxis:{format:"dd/M" },
timeline: { showBarLabels: false},
colors: ['#0f434c','#a30404'],
};
var ticks = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticks.push(data.getValue(i, 0));
var duration = (data.getValue(i, 4).getTime() - data.getValue(i, 3).getTime()) / 1000;
var days = parseInt( duration / 86400 )
var hours = parseInt( duration / 3600 ) % 24;
var minutes = parseInt( duration / 60 ) % 60;
var seconds = duration % 60;
var tooltip = '<div class="ggl-tooltip"><span>' +
data.getValue(i, 1) + '</span></div><div class="ggl-tooltip"><span>' +
data.getValue(i, 0) + '</span>: ' +
dateFormat.formatValue(data.getValue(i, 3)) + ' - ' +
dateFormat.formatValue(data.getValue(i, 4)) + '</div>' +
'<div class="ggl-tooltip"><span>Duração : </span>' +
days + 'd '+hours + 'h ' + minutes + 'm ' + seconds + 's ';
data.setValue(i, 2, tooltip);
}
options["hAxis"]["ticks"] = [0]
chart.draw(data, options);
}
}
Based on this link
This where I will go if i wanna change my date format
defaults: {
formatDate: function(date) {
var formatted = $.datePicker.utils.pad(date.getDate(), 2) + '/' + $.datePicker.utils.pad(date.getMonth() + 1, 2) + '/' + date.getFullYear();
return formatted;
},
parseDate: function(string) {
var date = new Date();
var parts = string.match(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
if ( parts && parts.length == 4 ) {
date = new Date( parts[3], parts[2] - 1, parts[1] );
}
return date;
},
selectDate: function(date) {
return true;
},
limitCenturies: true,
closeOnPick: true,
appendTo: null
},
How can I make this to MM/DD/YYYY? I tried everything I change it but when Im selecting dates the value goes on different dates
Here is the error
According to the documentation, this should work:
defaults: {
formatDate: function(date) {
//var formatted = $.datePicker.utils.pad(date.getDate(), 2) + '/' + $.datePicker.utils.pad(date.getMonth() + 1, 2) + '/' + date.getFullYear();
var formatted = $.datePicker.utils.pad(date.getMonth() + 1, 2) + '/' + $.datePicker.utils.pad(date.getDate(), 2) + '/' + date.getFullYear();
return formatted;
},
parseDate: function(string) {
var date = new Date();
if ( string ) {
formatted_date = string.split('/');
date = new Date( formatted_date[2], formatted_date[0] - 1, formatted_date[1] );
}
return date;
},
selectDate: function(date) {
return true;
},
limitCenturies: true,
closeOnPick: true,
appendTo: null
}
See it in action: Demo.
Try this out
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');
Following code is returning $("#dob") and $("#anniversery") date as 2014-04-01T00:00:00
My code
<script>
$(function() {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#customerName").autocomplete({
source: function(request, response) {
$.ajax({
url: "ajaxCustomer",
dataType: "json",
data: {
str: $("#customerName").val(),
maxRows: 12
},
success: function(data) {
response($.map(data.customerList, function(item) {
console.log(item);
return {
label: item.customerName,
value: item.customerName,
id: item.customerId,
address: item.address,
dob: item.dob,
mobno: item.mobno,
annversery: item.anniversery
}
}));
},
error: function(data) {
alert(data.supplierList);
console.log(typeof data);
console.log(data);
alert('error');
}
});
},
minLength: 1,
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#mobNo").val(ui.item.mobno);
$("#address").val(ui.item.address);
$("#dob").val(ui.item.dob);
$("#anniversery").val(ui.item.annversery);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
</script>
I want $("#dob") and $("#anniversery") its value in yyyy/mm/dd format
How to do this
I tried $("#dob").val(format_date(ui.item.dob));
function format_date(dt) {
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
document.write(dt);
document.write(year + '/' + month + '/' + day);
}
This is not working.
You have to cast the value you get from ui.item.dob to a Date.
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
Then in your format_date function, remove the extra line at the bottom and put a return statement instead:
function format_date(dt) {
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
return dt;
}
You could use MomentJS
Apply format :
$("#anniversery").text(moment(ui.item.annversery).format('YYYY/MM/DD'));
var date = "2014-04-01T00:00:00";
var newDate = date.split("T")[0].replace(/-/g, "/");
console.log(newDate);
=> 2014/04/01
As already #display_name pointed you missed to parse the Date. Here a more simplified version of your code:
function format_date(dt) {
var dateString = new Date(dt); //parse the date
var formatedDate = dateString.getFullYear() + "/" +
('0'+ (dateString.getMonth() +1)).slice(-2) + "/" +
('0'+ dateString.getDate()).slice(-2);
return formatedDate; //return the formatted date to the input field
}
Now you can
$("#dob").val(format_date(ui.item.dob)); // incase if it is a textbox
try this..
var thisDate = "2013-01-01 00:00:00";
var thisDateT = thisDate.substr(0, 10);
You should create new Date object before using get functions:
var date = new Date(dt);
And then you can get the proper values:
var dd = date.getDate();
and so on.