jquery make date from integer value - javascript

I am in need of making a program which can convert an integer number into a date using javascript/jquery. WhatI am thinking is to divide the numbers by 10 and then split them so then, depending upon the numbers I want to display the date in another input field.
The input given by the user should be like this:
910111
and the output should be
11/jan/1991
My code is:
<input type="text" id="id1"/>
<input type="text" id="id2" />
$("#id1").change('input', function(){
var input = $(this).val();
var remainder = [10];
var quotient = 0;
var divisor = 10;
var dividend = input;
var j=0;
var array1 = [10];
while(dividend >= 10)
{
remainder[j] = dividend % divisor;
quotient = dividend / divisor;
dividend = quotient;
j++;
}
});
The Updated code after the discussion is as follows which is not working when I pass the variable "input" instead of a hard coded value.
<html>
<head>
<title>
Inzamam Tahir
</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="moment.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var input = $("#id1").val();
$("#id1").change(function () {
var date = moment(input).format('DD/MM/YY');
$("#id2").val(date);
});
});
</script>
</head>
<body>
<input type= "text" id = "id1"/>
<input type = "text" id = "id2"/>
<input type = "submit" id = "id3"/>
</body>
</html>

Connect Moment.js and use this snippet:
moment("910111", "YYMMDD").format('DD/MMMM/YYYY'))
http://jsfiddle.net/400abej7/
Parse date: http://momentjs.com/docs/#/parsing/string-format/
Print (parsed) date: http://momentjs.com/docs/#/displaying/

You can create an array for months. And then you could do this
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
var input = "910111";
var output = input.replace(/(\d\d)(\d\d)(\d\d)/, function(m, g1, g2, g3){
return g3 + "/" + (months[g2-1]) + "/19" + g1;
});

best to assume 4 digit years, or you will have problems when you cross the 2000 boundary, but you can do this really simply with with modulus and divide. Much faster that most other solutions (looping or regEx etc):
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
$("#id1").change('input', function () {
var input = ~~$(this).val()
var year = ~~(input / 10000);
var month = ~~(input % 10000 / 100);
var day = ~~(input %100)
var date = "" + day +"/" +months[month-1]+ "/" + year
alert(date);
});
http://jsfiddle.net/TrueBlueAussie/na46owxu/2/
Notes:
~~ is a shortcut integer conversion.

Related

Google apps script for GSheet - Find today's date on column B and write current time on column C of the same row

I am trying to write an apps script and assign it to a button. When the button is pressed, it will activate a function I named clockin(). What this function does is to look for today's date on column B and write the current time on column C. The problem is this code is not writing any value on the defined cell which kinda sucks. I'm new to Javascript, hence requiring your assistance. My code is below:
function todayDateNowTime () {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date()
var month = monthNames[today.getMonth()]; //months from 1-12
var day = today.getDate();
var year = today.getFullYear();
var seconds = today.getSeconds();
var minutes = today.getMinutes();
var hour = today.getHours();
var todayDate = day+"-"+month+"-"+year;
var nowTime = hour+":"+minutes+":"+seconds;
console.log(todayDate);
console.log(nowTime);
return todayDate, nowTime;
}
function clockin(todayDate, nowTime) {
todayDate, nowTime = todayDateNowTime();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = 0; i<data.length;i++){
if(data[i][1] == todayDate) { //[1] because column B
var range = SpreadsheetApp.getActiveSpreadsheet().getActiveCell("C"+i)
range.setValue(nowTime);
}
}
}
I have made my gsheet publically available to view right here.
I have also included a screenshot here if it helps:
I made some small adjustments to your code. See if it now works?
function todayDateNowTime () {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date()
var month = monthNames[today.getMonth()]; //months from 1-12
var day = today.getDate();
day = day < 10 ? "0" + day : day;
var year = today.getFullYear();
var seconds = today.getSeconds();
var minutes = today.getMinutes();
var hour = today.getHours();
var todayDate = day+"-"+month+"-"+year;
var nowTime = hour+":"+minutes+":"+seconds;
return [todayDate, nowTime];
}
function clockin() {
var dateAndTime = todayDateNowTime();
var todayDate = dateAndTime[0];
var nowTime = dateAndTime[1];
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getDisplayValues();
for(var i = 0; i<data.length;i++){
if(data[i][1] == todayDate) { //[1] because column B
var range = sheet.getRange(i+1, 3)
range.setValue(nowTime);
}
}
}

Highlight current date

My function displays the current date along with the next 60 days however I want the current date to be highlighted. What would be the best approach?
var date = new Date();
var dayInt = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var dateRange = document.getElementById('calendar-table-range');
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("month").innerHTML = monthNames[month];
document.getElementById("year").innerHTML = year;
for(var day = 0; day < 60; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
var cell = document.createElement("li");
var cellText = document.createTextNode(day);
var date = ('0' + date.getDate()).slice(-2) + ' '
+ monthNames[date.getMonth()] + ' '
// + date.getFullYear();
cell.innerHTML = date;
dateRange.appendChild(cell);
}
Since you're always showing the next 60 days, the current date is always the first date in the list, so it's easy to target with a CSS selector. For example:
#calendar-table-range li:first-child {
background-color: yellow;
}
Another way to go about it is to create a timestamp in the same format as the dates in the range then search for it.
E.g. the following, which puts formatting into a separate function and removes code that wasn't being used:
function formatDate(d){
let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return ('0 ' + d.getDate()).slice(-2) + ' '
+ monthNames[d.getMonth()];
}
function highlightToday() {
let today = formatDate(new Date());
let cells = document.querySelectorAll('#calendar-table-range > li');
for (var i=0, iLen=cells.length; i<iLen; i++) {
if (cells[i].textContent == today) {
cells[i].style.color = 'red';
return;
}
}
}
var date = new Date();
var dayInt = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var dateRange = document.getElementById('calendar-table-range');
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("month").innerHTML = monthNames[month];
document.getElementById("year").innerHTML = year;
for(var day = 0; day < 6; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
var cell = document.createElement("li");
var date = formatDate(date);
cell.innerHTML = date;
dateRange.appendChild(cell);
}
<div id="month"></div>
<div id="year"></div>
<input type="button" onclick="highlightToday()" value="highlight today">
<ol id="calendar-table-range">
</ol>

Parsing or changing the date format with javascript

I'm trying to change the date format for some data coming in. I can change it to this format "02-10" but i wanted it to look like this "Feb 10 2015"
So far i have something like this that changes it to each day of the week, but i would like to change that. Here's what i have.
$scope.hourlyData = [];
var hourData = [];
var hourItem = [];
var dailyData = [];
var day;
var date;
var Everymonth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var item = ['Day', 'Number of Interactions', {role: 'style'}];
dailyData.push(item);
var dailyReports = $scope.tweetReports.dailyReports;
$scope.numberOfdailyReports = dailyReports.length;
for (var i = 0; i < dailyReports.length; i++) {
if (dailyReports[i] != null) {
//console.log("Tweets on " + dailyReports[i].day + ":" + dailyReports[i].tweets);
day = dailyReports[i].day.split(" ")[0];
date = dailyReports[i].day.split(" ")[1];
date = date.substr(date.indexOf('-') + 1);
if (numDays =< 7) {
day = day.toLowerCase();
day = day.charAt(0).toUpperCase() + day.substr(1);
} else {
day = date;
}
If you are open to use libraries, You can use momentJS like this
jsfiddle
var dateString = "2013-07-18";
var date = moment(dateString).format('MMM DD YYYY');

Show items in a box after clicking one by one using Javascript AngularJS

I have written a code, where it will show the next 12 months from current month. Suppose, now is Oct 2015, so it will show all next 12 months, that is upto Oct 2016. I am showing it in a list. But, I want to create a box with right-left arrow enabled. After clicking on left-right arrow it will show next item. After clicking on right arrow it will show next item and after clicking on left arrow it will show previous item. Data items will be shown in a box. Please check my below code, which will print next 12 months from current.
angular.module('picker', []).controller('pickercontroller', function($scope) {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i <= 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
date.setMonth(date.getMonth() + 1);
}
$scope.months = months;
});
<div ng-app="picker">
<div ng-controller="pickercontroller">
<li ng-repeat="currMonth in months">{{currMonth}}</li>
</div>
</div>
Also, check my fiddle :- http://jsfiddle.net/abhijitloco/cqbqow2L/
Check this code to see how you can change the selected month via ng-click
https://jsfiddle.net/jddg3som/
Controller
angular.module('picker', []).controller('pickerCtrl', function($scope) {
var date = new Date();
var months = [],
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
for (var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
date.setMonth(date.getMonth() + 1);
}
$scope.changeMonth = function(steps) {
if ($scope.monthIndex + steps >= 0 &&
$scope.monthIndex + steps <= 11
) {
$scope.monthIndex = $scope.monthIndex + steps;
$scope.monthName = $scope.months[$scope.monthIndex];
}
};
$scope.monthIndex = 0;
$scope.months = months;
$scope.monthName = months[0];
});
View
<div ng-app="picker">
<div ng-controller="pickerCtrl">
<h1> {{monthName}} </h1>
<button ng-click="changeMonth(1);">Next Month</button>
<button ng-click="changeMonth(-1);">Previous Month</button>
<li ng-repeat="currMonth in months">{{currMonth}}</li>
</div>
</div>
Use ng-click to handle button event and for next month check whether next month is available in months array or not. If available then set next month from array.
Same for previous month
angular.module('picker', []).controller('pickercontroller', function($scope) {
var date = new Date();
var months = [],
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
for (var i = 0; i <= 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
date.setMonth(date.getMonth() + 1);
}
$scope.months = months;
$scope.currMonth = months[0];
$scope.nextMonth = nextMonth;
$scope.prevMonth = prevMonth;
function prevMonth() {
var index = $scope.months.indexOf($scope.currMonth);
if (index != 0 && index < $scope.months.length) {
$scope.currMonth = $scope.months[index - 1];
}
}
function nextMonth() {
var index = $scope.months.indexOf($scope.currMonth);
if (index < $scope.months.length - 1) {
$scope.currMonth = $scope.months[index + 1];
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="picker">
<div ng-controller="pickercontroller">
<p>{{currMonth}}</p>
<button ng-click="prevMonth()">Previous Month</button>
<button ng-click="nextMonth()">Next Month</button>
</div>
</div>

JavaScript: missing logic when array iterate for missing value

I am trying to fill blank values when no data available for particular months. Here is plunker.. http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview
$scope.year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];
for(var i=0; i<total.length; i++){
if($scope.year[i].month === undefined){ //logic here to see absent month.
$scope.year.push(
{
"month":total[i],
"val":"0"
})
}
}
I have created array of default total months items for compare each month item from expected object, if the item is absent in expected object, need to create empty item or with value "0" in expected object itself.
You can do something like following
Js Update
var year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
// Current months array
var currentMonth = [];
angular.forEach(year, function(item){
currentMonth.push(item.month);
});
// iterating over months
for(var i=0; i<total.length; i++){
//$scope.year = [];
// checking if month is absent
if(currentMonth.indexOf(total[i]) === -1){ //logic here to see absent month.
year.push(
{
"month":total[i],
"val":"0",
"order" : i
})
} else {
year[currentMonth.indexOf(total[i])].order = i; // adding order
}
}
$scope.year = year;
Markup
<!-- Order by new property order -->
<td ng-repeat="item in year | orderBy: 'order'">
{{item.val}}
</td>
For reference - http://plnkr.co/edit/km6jLQv8wxm1XP8QCxvV?p=preview
year[i] is undefined, so you try get field of object that don't exist.
try it "if($scope.year[i] === undefined)"
Your idea of using orderBy won't work based on month because you aren't looking for an alphabetical sort.
Following creates array of months that exist in the data. Then it loops over all months in year and adds missing data. Finally sort the data based on months indexing
// create array of months available in data
var availableMonths = $scope.year.map(function(item){
return item.month;
});
// loop over all months and if it doesn't exist in data add it
total.forEach(function(mo){
if(availableMonths.indexOf(mo) ===-1 ){
$scope.year.push({"month":mo, "val":"0" })
}
});
// sort data using index of months
$scope.year.sort(function(a,b){
return total.indexOf(a.month) > total.indexOf(b.month);
});
remove the orderBy filter in html since data is already sorted
Steps 2 & 3 above could actually be combined to splice() the array so final order is correct but for ease of understanding I left them as separate operations
DEMO
Try this.
$scope.year = [
{"month":"jan", "val":"56"},
{"month":"feb", "val":"45"},
{"month":"mar", "val":"23"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];
for(var i=0; i<total.length; i++){
if(!$scope.year[i] || $scope.year[i].month === undefined){
$scope.year.push(
{
"month":total[i],
"val":"0"
})
}
}

Categories

Resources