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>'))
Related
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.
I am trying to convert two strings to dates but I am getting an NaN for an obviously date string.
Can anyone tell me why this happens?
Code:
function SortMaster() {
return function (a, b) {
var aValue = a, bValue = b, aLength = a.length, bLength = b.length;
var aType = Object.prototype.toString.call(aValue);
var bType = Object.prototype.toString.call(bValue);
var aasd = Date.parse(aValue);
var basd = Date.parse(bValue);
var aDate = (new Date(Date.parse(aValue))).toISOString().slice(0, 10).replace(/-/g, "");
var bDate = (new Date(Date.parse(bValue))).toISOString().slice(0, 10).replace(/-/g, "");
var highestValue = Math.max(aLength, bLength);
for (var i = 0; i < highestValue; i++) {
}
};
}
The value for a is a date string "21.10.2014 14:52:24"
The value for b is also a date string "04.04.2014 15:04:36"
The problem is that a is in dd.mm.yyyy format, seems like this is not recognizable as date by javascript which expected an mm.dd.yyyy format, so it threw an error because there's not such month as 21, but for b the error passed because the day was 04 which is less than 12 so it considered it as month while in fact it's day, so your format should not be dd.mm.yyyy
to demonstrate it check this jsFiddle
you see a2 is same date as a1 just in mm.dd.yyyy and it worked for a2 but a1 was invalid date
var a1 = '21.10.2014 14:52:24',
a2 = '10.21.2014 14:52:24',
b = '04.04.2014 15:04:36';
var dateA1 = new Date(Date.parse(a1)),
dateA2 = new Date(Date.parse(a2)),
dateB = new Date(Date.parse(b));
console.log('a1:' + dateA1); // error, Invalid Date
console.log('a2:' + dateA2);
console.log('b:' + dateB);
The issue was that the input string have had not the correct date format...
I have now created a function to create a correct format out of a date string.
function editDateString(dateString){
var dateStringSplits = dateString.split(' ');
var firstPart = dateStringSplits[0];
var secondPart = dateStringSplits[1];
var Year = firstPart.split(".")[2];
var Month = firstPart.split(".")[1];
var Day = firstPart.split(".")[0];
var Hour = secondPart.split(":")[0];
var Minute = secondPart.split(":")[1];
var Second = secondPart.split(":")[2];
return newDateString = Year + "-" + Month + "-" + Day + " " + Hour + ":" + Minute + ":" + Second;
}
Thanks to Mi-Creativity for his help!!!
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());
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.
I have a string which has a date in the format: dd-mm-yyyy
How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?
I have
var d = new Date(current_date);
d.setMonth(d.getMonth() + 1);
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();
alert(current_date_new);
but it complains that the string provided is in the incorrect format
EDIT: After a bit of fiddling, here's the solution:
First, split the string to individual parts.
var inputString = "12-2-2005";
var dString = inputString.split('-');
Then, parse the string to a datetime object and add 28 days (4 weeks) to it.
var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);
Finally, you can output the date
var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();
This code should return 12-3-2005.
CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.
EDIT2: To do padding, use this function:
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and change your output to
var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();
Check the updated fiddle.
There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:
var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)
date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();
This should be working:
var formattedDate = '01-01-2012',
dateTokens = formattedDate.split('-'),
dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );
jsfiddle: http://jsfiddle.net/uKDJP/
Edit:
Using Globalize you can format inFourWeeks:
Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012
Instead of writing your own parser for dates, I would use moment.js.
To parse your date:
var date = moment('14-06-2012', 'DD-MM-YYYY');
To add 4 weeks to it:
date.add('weeks', 4);
Or in one go:
var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);
And convert it to string:
var dateString = date.format('DD-MM-YYYY');