Save excel file with current date and time through javascript - javascript

I want to open the excel file and then save the excel file and the name will be file name + current date and time. I am not getting this result for date I have used Date()
var wshell;
var excel = new ActiveXObject("Excel.Application");
alert(excel);
var excel_file = excel.Workbooks.Open("book2.xlsx");
excel.Visible = true;
var objWorkbook = excel.Workbooks.Add();
var objWorksheet = objWorkbook.Worksheets(1);
objWorkbook.Worksheets(1).Activate;
objWorksheet.name = "test";
objWorksheet.Paste;
objWorksheet.columns.autofit;
window.clipboardData.setData("Text","");
var today = new Date();
document.write(today.toString());
excel_file.SaveAs("d:\\board.xls"+ (today.toString()));
alert("data saved");

today contains an illegal character (:) to use in a file name. You need to clean your date, for example something like this:
var today = new Date().toString().replace(/[^\w]/g, '');
And when saving, the timestamp should be a part of the file name instead of the extension:
excel_file.SaveAs("D:\\board" + today + ".xls");
Instead of .toString().replace() you can format the timestamp to look like you want with methods of Date object.
EDIT
Here's the code with which you can modify your dates. I've simplified getDate() for you, hence you can modify it to return a date in what ever form you want.
var today = new Date(),
time = today.toTimeString().split(':').join('').substr(0, 4),
timestamp = getDate('dd_mm_yyyy', today) + '_' + time;
function getDate (mode, userdate) {
var dte = userdate || new Date(),
d = dte.getDate().toString(),
m = (dte.getMonth() + 1).toString(),
yyyy = dte.getFullYear().toString(),
dd = (d.length < 2) ? '0' + d : d,
mm = (m.length < 2) ? '0' + m : m,
yy = yyyy.substring(2, 4);
switch (mode) {
case 'dd_mm_yyyy': return dd + '_' + mm + '_' + yyyy;
case 'yyyymmdd': return yyyy + mm + dd;
default: return dte;
}
}
timestamp contains a date in wanted form after run the code above.

Related

How can I get the value of a key from JSON to JS?

I'm working on an application that requires dates to be fed from JS and check in a JSON table what the "Letter" of the day is.
How can I take the JS date string that I've created (yyyy,mm,dd), and find the value of the corresponding key?
I have tried taking the string, stringifying it, and pushing it through a JS function.
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var dateStr = year + "/" + month + "/" + date;
console.log(dateStr);
dateJSON = JSON.stringify(dateStr)
console.log(dateJSON)
alert(testVar.dateJSON)
var testVar = { //In a JS file
"2019-11-06": "D",
"2019-11-08": "A_con" //continues for a very long time.....
}
For "2019-11-08" I would like to have variable "letterDay" equal "A_con".
My code thus far returns "undefined" when I pull "testVar.dateJSON"
I think it is far simpler than this, your data keys are in format yyyy-mm-dd while you're dateStr is in the format yyyy/mm/dd here is a simple snippet
var testVar = { //In a JS file
"2019-11-09": "D",
"2019-11-08": "A_con" //continues for a very long time.....
}
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
// Your mistake was here, the separators were '/'
var dateStr = year + "-" + month + "-" + date;
console.log(dateStr);
// Get the value dynamically
// when you have a dynamic key use testVar[dateStr]
// testVar.dateStr will literally look for a key called "dateStr" it will not evaluate the value of dateStr
console.log(testVar[dateStr]);
You formatted your dateStr variable the wrong way ("/" instead of "-").
var testVar = { //In a JS file
"2019-11-06": "D",
"2019-11-08": "A_con" //continues for a very long time.....
}
var d = new Date('November 06, 2019 23:15:30');
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var dateStr = year + "-" + month + "-" + (day > 9 ? day : '0' + day);
console.log(testVar[dateStr]); // D
Have your tried using JSON.parse()?
So: JSON.parse(testVar); and then modify your code and variables from there.

Javascript format date

I have a date string which coming from the db as follows
/Date(1469167371657)/
Is there any way to convert this date to following format using javascript
MM/DD/YYYY HH:MM
I've searched a lot but unble to find a solution
In plain javascript you have to write your own function for string format a date, for example for your string format:
var date = new Date(1469167371657);
function stringDate(date) {
var mm = date.getMonth()+1;
mm = (mm<10?"0"+mm:mm);
var dd = date.getDate();
dd = (dd<10?"0"+dd:dd);
var hh = date.getHours();
hh = (hh<10?"0"+hh:hh);
var min = date.getMinutes();
min = (min<10?"0"+min:min);
return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min;
}
console.log(stringDate(date));
drier code version
var date = new Date(1469167371657);
function stringDate(date) {
return ("0" + (date.getMonth() + 1)).slice(-2)+'/'
+("0" + date.getDate()).slice(-2)+'/'
+date.getFullYear()+" "
+("0" + date.getHours()).slice(-2)+':'
+("0" + date.getMinutes()).slice(-2)
}
console.log(stringDate(date));
with pure js you can do the folowing
var d = new Date();
console.log(d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes())
You can use - http://momentjs.com/ and have it done like:
moment(1469167371657).format('MM/DD/YYYY HH:MM')
You can do this with the following steps:
1) convert the timestamp to a date object.
var timestamp = "/Date(1469167371657)/"; // However you want to save whatever comes from your database
timestamp = timestamp.substr(timestamp.indexOf("(")+1); // gives 1469167371657)/
timestamp = timestamp.substr(0,timestamp.indexOf(")")); // gives 1469167371657
var d = new Date(timestamp);
2) set it to your format
function leadZero(i) {if(i < 10) {return "0"+i;} return i;} // Simple function to convert 5 to 05 e.g.
var time = leadZero(d.getMonth()+1)+"/"+leadZero(d.getDate())+"/"+d.getFullYear()+" "+leadZero(d.getHours())+":"+leadZero(d.getMinutes());
alert(time);
Note: the date / timestamp you provided is too high for javascript to understand, so this example will not work correclty
I believe that number is milliseconds so to convert it to date, you would do this:
var time = new Date().getTime();
var date = new Date(time);
alert(date.toString()); // Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
var time=1469167371657;
var date = new Date(time);
alert(date.toString());

convert xml date and time using javascript

I am pulling the some information from a stock feed. the time stamp for last update comes in like this:
2016-02-10 13:32:41
How do I format it to be like:
1:32:41pm
2/10/2016
Here is my variable declaration:
time = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
You could turn the string into a valid javascript date and then use the date methods to display it how you want to. For example to turn it into a javascript date, split it into its parts and then assemble.
var dateAndtime = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
var date = dateAndtime.split(' ')[0];
var time = dateAndtime.split(' ')[1];
var year = date.split('-')[0];
var month = date.split('-')[1]-1;
var day = date.split('-')[2];
var hour = time.split(':')[0];
var minute = time.split(':')[1];
var second = time.split(':')[2];
var d = new Date(year, month, day, hour, minute, second);
There is no need to create a Date, you can just parse and reformat the string. You have to parse the string anyway, reformatting without a Date is just more efficient.
// 2016-02-10 13:32:41 => m/dd/yyyy h:mm:ssap
function reformatDateString(s) {
var b = s.split(/\D/);
var ap = b[3] < 12? 'am':'pm';
var h = b[3]%12 || 12;
return h + ':' + b[4] + ':' + b[5] + ap +
'\n' + +b[1] + '/' + b[2] + '/' + b[0];
}
document.write(reformatDateString('2016-02-10 13:32:41').replace('\n','<br>'))
document.write('<br>');
document.write(reformatDateString('2016-12-09 03:02:09').replace('\n','<br>'))

If Date is empty format_date() returns NaN/NaN/NaN insted of no value

I am using jquery autocomplete onselect it is showing data in different text field. I am showing formatted date in #dob and #anniversery by using format_date() function
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#customerName").val(ui.item.value);
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
var datefield1 = new Date(ui.item.anni);
$("#anniversery").val(format_date(datefield1));
$("#address").val(ui.item.address);
$("#mobNo").val(ui.item.mobno);
},
});
function format_date(dt) {
alert(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;
}
});
Above code is working properly if ui.item.dob and ui.item.anni is not null.
In case of null it is showing NaN/NaN/NaN
If date value is empty it should not show anything in textbox.
alert(dt) prints Invalide date.
How to resolve this.
You can check whether a Date instance is an invalid date by checking one of the properties for NaN:
function format_date(dt) {
if (isNaN(dt.getFullYear())) return "";
// ...
}
In your function, check that the Date object is okey using isNaN function. Also, there's an easier way of formating the date as you want, with out all the ifs:
function format_date(dt) {
if(isNaN(dt.getTime()) return "";
return dt.getFullYear + '/' + String('00' + (dt.getMonth() + 1)).slice(-2) + '-' + String('00' + dt.getDate()).slice(-2);
}
Also good to know is that initializing a Date object like var datefield = new Date(ui.item.dob); has a bit poor browser support (
A more safe way of doing it is to initialize the Date object without any proporties, var datefield = new Date(); and the using the Date set*() functions to set the time. A whole lot more code, but if you need it to work in old browsers...
Example
http://jsfiddle.net/HMb68/
var inDateTime = '2014-07-26 17:52:00',
inDateTimeSplit = inDateTime.split(' '),
inDateParts = inDateTimeSplit[0].split('-'),
inTimeParts = inDateTimeSplit[1].split(':'),
outDate = new Date;
outDate.setFullYear(parseInt(inDateParts[0], 10));
outDate.setMonth((parseInt(inDateParts[1], 10) - 1));
outDate.setDate(parseInt(inDateParts[2], 10));
outDate.setHours(parseInt(inTimeParts[0], 10));
outDate.setMinutes(parseInt(inTimeParts[1], 10));
outDate.setSeconds(parseInt(inTimeParts[2], 10));
outDate.setMilliseconds(0);
console.log(outDate);

Convert UTC Date to dd/mm/yyyy Format

I am having some difficulties when trying to convert UTC Date format to dd/mm/yyyy in JavaScript:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = new Date(date.toLocaleDateString());
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
I tried with this, but it returns me an invalid date. So I changed to this:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCMonth() + 1) + "/" + (d.getUTCDate() + 1) + "/" + (d.getUTCFullYear()));
}
However, it still returning me invalid Date. I wonder is there any possible way to change the date format of Fri May 31 2013 17:41:01 GMT+0200 (CEST) to dd/mm/yyyy?
Thanks in advance.
var d = new Date();
var n = d.toLocaleDateString();
This will be more superior in build JS method!
function formatDate(d)
{
date = new Date(d)
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
return d = dd+'/'+mm+'/'+yyyy
}
Try it:
Date.parseExact(Your_Date, 'dd/MM/yyyy').toString('MM/dd/yyyy');
or
Date.parseExact(Your_Date, 'MM/dd/yyyy').toString('dd/MM/yyyy');
Month is 0 indexed, but day is not. You don't need to add 1 to your day.
Also, you're formatting it for MM/dd/yyyy, not dd/MM/yyyy.
solution:
var launchDate = attributes["launch_date"];
if (isBuffering) {
var date = new Date(launchDate);
var d = formatDate(new Date(date.toLocaleDateString()));
launchDate = ((d.getUTCDate())+ "/" + (d.getUTCMonth() + 1) + "/" + (d.getUTCFullYear()));
}

Categories

Resources