I have a string that contains a datetime in the following format
2016-07-30 00:00:01.0310000
I need to convert this to a datetime object in JavaScript retaining the sub-seconds.
If I use
var d = new Date('2016-07-30 00:00:01.0310000');
Everything after 01 is dropped, how can I efficiently achieve this?
You'll have to parse the string yourself (which is quite simple, the only tricky bit is trailing zeros on the milliseconds value) and build the date using the Date(years, months, days, hours, minutes, seconds, milliseconds) constructor. Or use a library and a format string.
Here's an example:
var str = "2016-07-30 00:00:01.0310000";
var parts = /^\s*(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)\s*$/.exec(str);
var dt = !parts ? null : new Date(
+parts[1], // Years
+parts[2] - 1, // Months (note we start with 0)
+parts[3], // Days
+parts[4], // Hours
+parts[5], // Minutes
+parts[6], // Seconds
+parts[7].replace(/0+$/, '') // Milliseconds, dropping trailing 0's
);
if (dt.toISOString) {
console.log(dt.toISOString());
} else {
console.log("date", dt.toString());
console.log("milliseconds", dt.getMilliseconds());
}
In the regex, \d means "a digit" and {x} means "repeated x times".
The !parts ? null : new Date(...) bit is so that if the string doesn't match the format, we get null rather than an error.
The milliseconds are saved (31), but what comes after that is not saved, because javascript does not support it.
You could use library like Moment JS, You can read more http://momentjs.com/docs/
var day = moment("2016-07-30 00:00:01.0310000");
console.log(day._d); // Sat Jul 30 2016 00:00:01 GMT+0100 (WAT)
Related
I am trying to compare a time in string format to the current time. I've tried setting up two Date objects and calling .Now() on both of them, then on one of them adjusting the time to the time that is in string format by splitting it and parsing both the hours and minutes to integers, but I get the following error:
setHours is not a function
The 'cutoff' value I'm using is '15:00' and when following in the debugger I can see this splits in to split[0] = 15 and split[1] = 00 (this is before they are parsed into integers.
var cutoff = data.CutOff;
var split = cutoff.split(":");
var today = Date.now();
var hours = parseInt(split[0]);
var min = parseInt(split[1]);
today.setHours(hours, min);
if (Date.now() < today) {
// Do Something
}
You want to do new Date() as opposed to Date.now()
new Date creates a Date instance which allows you to access the Date methods.
Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
I am reading excel data using php and JavaScript. Storing results in variable and showing it on the page.
Simple code example:
var yearend = "< ? php echo ($connection->sheets[0]["cells"][2][5]); ? >";
This works for text and fields with number. But when I format cell as "Date" it returns the values, such as.
Excel field is: 31-Dec-2015 - JavaScript returns value: 40542
I know it is a MS DATEVALUE formatting.
But i need to convert it to date using JavaScript so it shows 31-Dec-2015 or 31 December 2015 only.
So in short:
From Excel 40542 to JavaScript 31 December 2015.
Also, I only need as above, without trailing time and locations, so removing:
00:00:00 00:00 GMT
Also is it possible modify the date to +1 day or -1 day?
//Convert Excel dates into JS date objects
//#param excelDate {Number}
//#return {Date}
function getJsDateFromExcel(excelDate) {
// JavaScript dates can be constructed by passing milliseconds
// since the Unix epoch (January 1, 1970) example: new Date(12312512312);
// 1. Subtract number of days between Jan 1, 1900 and Jan 1, 1970, plus 1 (Google "excel leap year bug")
// 2. Convert to milliseconds.
return new Date((excelDate - (25567 + 1))*86400*1000);
}
try this
toDate(serialDate, time = false) {
let locale = navigator.language;
let offset = new Date(0).getTimezoneOffset();
let date = new Date(0, 0, serialDate, 0, -offset, 0);
if (time) {
return serialDate.toLocaleTimeString(locale)
}
return serialDate.toLocaleDateString(locale)
}
Use the following php function to covert the datevalue into a php timestamp. You could then use standard date functions to format however you wish
function xl2timestamp($xl_date){
return ($xl_date - 25569) * 86400;
}
I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );
I have been using
timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toString());
And it will output for example:
Tue Jul 6 08:47:00 CDT 2010
//24 hour time
Screen real estate is prime, so I would like to take up less space with the date and output:
mm/dd/yy hh:mm
//also 24 hour time
Just add an extra method to the Date object, so you can reuse it as much as you want. First, we need to define a helper function, String.padLeft:
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
After this, we define Date.toFormattedString:
Date.prototype.toFormattedString = function () {
return [String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0'),
String(this.getFullYear()).substr(2, 2)].join("/") + " " +
[String(this.getHours()).padLeft(2, '0'),
String(this.getMinutes()).padLeft(2, '0')].join(":");
};
Now you can simply use this method like any other method of the Date object:
var timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toFormattedString());
But please bear in mind that this kind of formatting can be confusing. E.g., when issuing
new Date().toFormattedString()
the function returns 07/06/10 22:05 at the moment. For me, this is more like June 7th than July 6th.
EDIT: This only works if the year can be represented using a four-digit number. After December 31st, 9999, this will malfunction and you'll have to adjust the code.