How to convert a date format in semnatic-UI-Calendar? - javascript

I am developing a web application where I am using this module as a datepicker calendar:
https://github.com/mdehoog/Semantic-UI-Calendar
By default settings, when I select a date, it is input in the following format : 'October 12, 2016'
I want the selected date to be input in the following format '2016-10-12'
With reference to its API, I am using the following javascript code:
<script>
$(document)
.ready(function() {
$('.date_selecter').calendar({
type: 'date'
});
})
;
</script>
Does anyone know how to get the date in the format of 'yyyy-mm-dd'?

You can use the onChange event for the calendar instead of reading the value from the text field - this will give you a JavaScript Date object which you can then format yourself.
$(document).ready(function() {
$('.date_selecter').calendar({
type: 'date',
onChange: function(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
// everything combined
console.log(year + '-' + month + '-' + day);
}
});
});

Related

Rearrange date fromat

Is there a better way to write this code? I'm taking a "date" parameter (which is a string in this case) thats formatted in one of two ways mm/dd/yy' or m/d/yy and I need to reformat it to look like this yyyymmdd
functionName = function(date){
var month = "", day = "", year = "";
if(!date.length) return;
else {
date.slice(0, 2) < 10 ? month = '0' + date.slice(0, 2) : month = date.slice(0, 2);
date.slice(3, 5) < 10 ? day = '0' + date.slice(3, 5) : day = date.slice(3, 5);
year = "20" + date.slice(6, 8);
}
return year + month + day;
}
Also how should I check to see if the date was in the 1900's and format it accordingly?
There is no way to make a full year from a two digit year, it's missing information.
However you could simplify your function using .split() and .padStart()
function FormatDate (date) {
if (date) {
date = date.split('/'); //date[0] = month, date[1] = day, date[2] = year
return date[2] + date[0].padStart(2, '0') + date[1].padStart(2, '0');
}
}
console.log(FormatDate('07/09/20')); //outputs 200709

How to highlight custom date in bootstrap date picker

Im using angularjs for my project and bootstrap date-picker for select date.
In my project there is 2 input for select From date and To date. For the From date can select only today date, for the To date calculation i have add 1 year for from date using JavaScript and bind to To Date input. Data binding part is working fine. but when i click on To date its not show highlighted date in date-picker. Can i know how to highlight Today.
These are the option currently im used.
autoclose: true,
todayHighlight: true
In HTML You can use this.
<input name="dateInput" type="date" ng-model="TodayDate"/>
And In Controller you can get new Date(), So You can Assign the date to the ng-model.
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
if (month < 10){
month = "0" + month;
};
if (day < 10) {
day = '0' + day;
}
$scope.TodayDate = year + "-" + month + "-" + day;

Time conversion to ISO string is not correct with text field displayed

I have a text field in an MVC application that displays the date and time. The date is created using a datepicker and the time I add to the text field.
An example of the text is as follows:
10/23/2015 12:00 AM
I want to create a Date object with this time in ISO 8601 format. The date will be used to create an event in a fullcalendar jquery plugin.
When I try to create the Date object, the ISO string is:
2015-10-23T04:00:00.000Z
It should be 2015-10-23T00:00:00.000Z to represent midnight on that day.
This is my code:
<label id="schedule_start_date_lbl">Start Date: </label>
<input id="schedule_start_date" type="text" />
var startDayIndex = getDayIndex($('#rotation_start_time_txt').val());
$("#schedule_start_date").datepicker({
minDate: 0,
beforeShowDay: function (date) { return [date.getDay() == startDayIndex, ""] },
onSelect: function (dateText) {
$('#schedule_end_date').datepicker('option', 'minDate', dateText);
},
onClose: function (selectedDate) {
var rotation_txt = $('#rotation_start_time_txt').val();
var time = rotation_txt.substr(rotation_txt.indexOf(',') + 1);
$(this).val(selectedDate + time.toString(' HH:mm tt').toString());
}
});
$("#rotation_schedule_btn").click(function () {
//text value in schedule_start_date is: 10/23/2015 12:00 AM
var startDate = new Date($('#schedule_start_date').val()).toISOString();
//Value displayed is 2015-10-23T04:00:00.000Z
alert('startDate: ' + startDate);
});
Why is the time value off by 4 hours?
Thanks
UPDATE
I need to add to the Date objects after they are created. Creating the Date object using the function in the answer below is not creating it in UTC format. It can be displayed in that format but when I am creating events in the fullcalendar control, the date must be in UTC format and they are not.
This is my function to create a schedule:
$("#rotation_schedule_btn").click(function () {
//create member list order
var memberList = [];
$("#rotationList li").each(function () {
memberList.push({
id: $(this).attr('id'),
name: $(this).text(),
color: $(this).css('background-color')
})
});
//start and end date and time for new schedule
var startDate = convertTextToDate($('#schedule_start_date').val())
var endDate = convertTextToDate($('#schedule_end_date').val());
//remove events between startDate & endDate
$('#edit_calendar').fullCalendar('removeEvents', function (event) {
if (event.start.toDate() >= startDate && event.start.toDate() <= endDate
|| event.end.toDate() >= startDate && event.end.toDate() <= endDate) {
return true;
}
});
//Create events from rotation schedule selected
var newEvents = [];
var rotation_length = $('#rotation_type_select option:selected').val();
var rotation_start_date = new Date(startDate.toISOString());
var rotation_end_date = new Date(startDate.toISOString());
//End date is to midnight
endDate.setMinutes(endDate.getMinutes() + 1);
rotation_end_date.setDate(rotation_end_date.getDate() + parseInt(rotation_length));
var member_index = 0;
while (rotation_end_date <= endDate)
{
// alert('start date: ' + rotation_start_date.toISOString() + ' end date: ' + rotation_end_date.toISOString());
var event = new Object();
event = {
title: memberList[member_index].name,
start: new Date (rotation_start_date.toISOString()),
end: new Date (rotation_end_date.toISOString()),
objectID: memberList[member_index].id,
color: memberList[member_index].color,
allDay: true,
textColor: 'white'
};
newEvents.push(event);
eventsAdded.push(event);
rotation_start_date.setDate(rotation_start_date.getDate() + parseInt(rotation_length));
rotation_end_date.setDate(rotation_end_date.getDate() + parseInt(rotation_length));
if ((memberList.length - 1) == member_index) {
member_index = 0;
}
else {
member_index++;
}
}
//Render events on calendar
$('#edit_calendar').fullCalendar('addEventSource', newEvents);
}); //end create schedule button click
The function to convert the dates is the same as below but I renamed the function:
function convertTextToDate(dateValue)
{
var dateArray = dateValue.split(/\D/);
var pm = /pm$/i.test(dateValue);
var hour = (+dateArray[3] || 0) % 12 + (pm ? 12 : 0);
var date = new Date(Date.UTC(dateArray[2], dateArray[0] - 1, dateArray[1], hour, +dateArray[4] || 0, +dateArray[5] || 0));
return date;
}
What am i doing wrong?
Date.prototype.toISOString() is based on a 0 offset UTC timezone. So it is trying to normalize your current timezone back to 0 UTC, because when you do new Date() you create a new date based on your current time zone, that is why the method is trying to revert your date back to UTC time zone. You are probably right now in a time zone which is 4h behind UTC.
http://devdocs.io/javascript/global_objects/date/toisostring
In order to fix this, just append your string with " UTC" and it will no longer do the timezone shifting:
10/23/2015 12:00 AM UTC
It will generate:
"2015-10-23T00:00:00.000Z"
Do not use the Date constructor to parse strings, particularly non-standard strings. Ever. Manually parse the string.
Since you have a fixed format, it's pretty straight forward to create a date based on UTC with the format in the OP
// Parse date format mm/dd/yyyy hh:mm:ss AP as UTC
function parseMDYA(s) {
var b = s.split(/\D/);
var pm = /pm$/i.test(s);
var h = (+b[3]||0)%12 + (pm? 12 : 0);
return new Date(Date.UTC(b[2], b[0]-1, b[1], h, +b[4]||0, +b[5]||0));
}
var s = '10/23/2015 12:00 AM';
var d = parseMDYA(s);
document.write('Input string: ' + s +
'<br>UTC time: ' + d.toISOString() +
'<br>Local time: ' + d
);
Time parts that aren't supplied are treated as 0.

A twofold javascript function to convert a long date and return today's date in mm-dd-yyyy format

I need your help,
I can't seem to find any other help on this on the internet, because it seems its either one way ot the other. What I would like to be able to do is to create a combined, two-fold javascript function that would convert a long date string into the mm-dd-yyyy format, and when the same function is called again with no string specified to convert, to just return todays date in mm-dd-yyyy format.
Example:
getDate(Fri May 22 2015 13:32:25 GMT-0400)
would return: 05-22-2015
getDate()
would return today's date of 05-23-2015
Hi this should do the trick
FORMAT: mm-dd-yyyy
function addZeroIfRequired(dayOrMonth) {
return dayOrMonth > 9 ? dayOrMonth : "0"+dayOrMonth;
}
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return addZeroIfRequired((date.getUTCMonth()+1)) + "-" +
addZeroIfRequired(date.getDate())+ "-" +
date.getUTCFullYear();
}
console.log(getDate()); // 05-23-2015
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400")); 05-22-2015
NOTE: the +1 after the getUTCMonth().
JSFiddle. Open the console to see the result. https://jsfiddle.net/wt79yLo0/2/
ISO FORMAT: yyyy-mm-dd
Just in case someone is interested in the opposite format, the code would be much nicer and neater:
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return date.toISOString().substring(0, 10);
}
console.log(getDate());
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400"));
https://jsfiddle.net/wt79yLo0/
First I would recommend a very powerful library for JS called Moment.js which solves all this kind of problems.
But if you only want a snippet, here is my proposal:
function twoDigits(num) {
return ("0" + num).substr(-2);
}
function getFormattedDateDMY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [day,month,year].join(separator);
}
function getFormattedDateMDY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [month,day,year].join(separator);
}
console.log(getFormattedDateDMY(new Date(), "-")); //23-04-2015
console.log(getFormattedDateMDY(new Date(), "-")); //04-23-2015
With getDate(), getMonth() and getFullYear(). You have to set a "0" before the months and days which are < 10. GetMonth() starts with 0, therefore (getMonth() + 1).
function getFormattedDate() {
var date = new Date();
var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
var year = date.getFullYear();
var formattedDate = day + "-" + month + "-" + year;
return formattedDate;
}
console.log(getFormattedDate());
Demo

Format date string for Google calendar chart [duplicate]

I have a string that represent a data like 2014-July-2014. I am formatting this date in javacript so that I can use it as an argument for Google calendar chart.
E.g.
var x = "2014-July-12";
var splitted = x.spilt('-');
// to get "2014" at index [0], "July" at index [1] and "12" at index [2].
I then use a key value array to get the months in number.
Then I populate Google calendar data table with..
data.addRow([new Date(ParseInt("splitted[0]"),months.splitted[1], ParseInt("splitted[2]")), dataValues[i].Value]);
I use ParseInt() to convert from string to numbers since new Date(yyy,mm,dd) taks only integers as arguments.
I cannot get this calendar working. I searched a lot on the net but cannot find a good example of how to populate Google calendar calendar chart from json file.
Can you guys take a look and guide me how to do this task and explain were i'm wrong.
Thanks in advance.
Draw Calendar Chart Function
function drawCalendarChart(jsonObj) {
var dataValues = eval(jsonObj)
var data = new google.visualization.DataTable(dataValues);
data.addColumn({ type: 'date', id: 'Date' });
data.addColumn({ type: 'number', id: 'Reports' });
for (var i = 0; i < dataValues.length; i++) {
var date = new Date(dataValues[i].Date);
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var Formatted = "" + year + "," + month + "," + day;
// data.addRow([new Date(dataValues[i].Date), dataValues[i].Frequencies]);
data.addRow([new Date(Formatted), dataValues[i].Frequencies]);
}
var options = {
title: "Calendar Chart",
height: 350
};
var chart = new google.visualization.Calendar(document.getElementById('chart'));
chart.draw(data, options);
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(data, { showRowNumber: true });
}
I added the function i'm using to draw the chart. The data is giving a NaN,NaN error. The frequency is getting the right values. So it must be related to date formatting.
This is the test string i'm using.
[
{
"Date": "2014-January-15",
"Frequencies": 11
},
{
"Date": "2014-January-8",
"Frequencies": 22
},
{
"Date": "2014-January-10",
"Frequencies": 11
}
]
Keep it simple, this should work:
data.addRow([ new Date(dataValues[i].Date), dataValues[i].Frequencies ]);
UPDATE
It worked for me, here you have a working fiddle with the code.
Here is how you can convert your string date values to numbered date.
var date = new Date("12-January-2014");
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var Formatted = "" + year+"," + month+"," + day;
EDIT
var vt= new Date(year, month, day);
alert(vt);
Now you can use this variables in data function as needed.
Here is code
Hope it helps..!!!

Categories