I've got a column of datetimes in the following funky format:
2016-07-07 12:34:47 -0700
I understand that I can convert this to a usable format by using the .toISOString() function in JS/Apps Script.
Not to be presumptuous, but can anybody easily manage this feat, help me take the first step, or even point me in the direction perhaps of a published Apps Script that can do this?
Thanks so much :)
Return the Date object as a string, using locale conventions:
var d = new Date();
var n = d.toLocaleDateString();
Convert today's date into a readable string:
var d = new Date();
var n = d.toDateString();
Other functions that might be useful:
.toUTCString()
.toString()
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 months ago.
When working with the task, it became necessary to get dates from html, and to find out the time difference between them:
var now_time_div = document.getElementById("time_now_of");
var start_time_div = document.getElementById("time_when_start_of");
var time_now = now_time_div.textContent || now_time_div.innerHTML;
var time_start = start_time_div.textContent || start_time_div.innerHTML;
After that, without thinking about the format of the data, I wanted to find the time difference in ms:
var worked_time = time_now - time_start
That didn't work, because we are working with a string.
After entering the directory, I found the Date.parse() function, which returns the amount of time that has passed since the given date:
var worked_time = Date.parse(time_start);
but it turned out that it works only with a correctly submitted strig, for example
We need to have:
Date.parse('01 Jan 1970 00:00:00 GMT');
We have:
Date.parse('21.09.2022, 15:34:21')
Maybe someone knows an easy way to implement this without rebuilding the string?
If you don't want to bring in a library like moment.js, you can just massage the date string a bit so it can be parsed correctly
const dateString = '21.09.2022, 15:34:21';
const curDate = dateString.split(',')[0].substring(0, 10).split('.');
const curTime = dateString.split(',')[1];
const parsed = `${curDate[1]}'/'${curDate[0]}'/'${curDate[2]} ${curTime}`;
console.log(new Date(parsed).toString()); // Properly formatted date
You can used this parsed variable to compare to other properly formatted dates
You can use moment.js to parse custom date formats just as in for example Java:
https://momentjs.com/docs/#/parsing/string-format/
After that you can simply convert it to a js date using the toDate function: https://momentjs.com/docs/#/displaying/as-javascript-date/
Edit Example:
var mDate = moment('2022-09-21 10:15:00', 'YYYY-MM-DD HH:mm:ss');
var jsDate = mDate.toDate();
I'm working with Javascript within Google Sheets, and I'm having trouble converting or parsing a formatted timestamp, to ultimately extract the day as a numerical value.
My code:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
Logger.log(date.getDay());
The output:
[19-06-10 17:40:56:107 BST] NaN
My goal is to extract the day number, for example, "18" from that timestamp.
However, it doesn't seem to convert it. I suspect my timestamp isn't in the correct format for the date() function, so it's about creating a function to parse it.
Hopefully, you can help me with that! :) Thank you so much.
The date object has a method like this for getting the day of the month as a number (1-31).
date.getDate();
18 is date.
var shopifyTimestamp ="2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
console.log(date.getDate());
JavaScript's Date constructor supports ISO 8601 date strings. Without using any libraries, you can do something like this:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
// will produce `2019-05-18T13:21:17+0100`
var isoDate = shopifyTimestamp.slice(0, 10)
+ 'T' + shopifyTimestamp.slice(11, 19)
+ shopifyTimestamp.slice(20);
var date = new Date(isoDate);
console.log(date.getDate()); // 18
Also note that you're looking for date.getDate(), rather than date.getDay(). The latter returns the numerical date of the week.
I have a system that returns a JSON object that contains dates in string format.
These dates are in the format "2012-10-19 06:05:38 GMT" (no... I'm stuck with them like this)
So I need to get this into a date object (d) ready to output as d.toLocaleDateString()
In chrome it works perfectly by just passing the string to a new Date (Bad bad Chrome - makes Eric lazy), but of course it fails in FF and IE
I can fix it by splitting the string but its not pretty and I've not figured out dealing with the offsets from GMT.
There must be a more elegant way...?
I'm sure someone here can do it in one line.
It's not quite a one-liner, but if you know all your dates will be GMT, something like the following should work:
function parseDate(dateString) {
// [y, m, d, hr, min, sec]
var parts = dateString.match(/\d+/g);
// Months are 0-indexed
parts[1] -= 1;
return new Date(Date.UTC.apply(Date, parts));
}
If I were you, and had access to the serverside script gathering that information (and outputting it) I would convert the date into a unix timestamp, and then make Javascript process that using the Date constructor easily.
EDIT: You can use strtotime() function to convert the string date into numeric unix timestamp if you're using PHP.
If you know the exact format, you could use a library such as Moment.js: Documentation for Moment.js.
To parse:
var dateString = "2012-10-19 06:05:38 GMT".replace(" GMT", "");
var date = moment(dateString, "YYYY-MM-DD HH:mm:ss");
You can just parse the dateString manually,and pass the Date the Date constructor exactly:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var dateString = "2012-10-19 06:05:38 GMT".split(" "),
date = dateString[0].split("-"),
time = dateString[1].split(":");
var dateObj = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);
I am debugging a small application with some functionality which would only run in Chrome. The problem lies in a datepicker where you choose a date and time and the datepicker concaternates it into a datetime-string.
Anyway the string looks like this: 2012-10-20 00:00.
However, the javascript that uses it now just takes the string and initialize an object with it like this: new Date('2012-10-20 00:00');
This is resulting in an invalid date in Firefox, IE and probably all browsers but Chrome.
I need advise in how I best could transform this datestring to a Date object in javascript. I have jQuery enabled.
Thanks for your sage advise and better wisdom.
If the string format is always as you state, then split the string and use the bits, e.g.:
var s = '2012-10-20 00:00';
var bits = s.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2], bits[3], bits[4]);
It's just the simplify version:
var newDate = new Date('2015-04-07 01:00:00'.split(' ')[0]);
if str = '2012-10-20 00:00'
new Date(str.split(' ')[0].split('-').join(',') + ',' + str.split(' ')[1].
split('-').join(','))
should do the trick
use parseExact method
var date = new Date.parseExact(dateString, "yyyy-mm-dd hh-mm");
Hey, just wondering how to convert an HH:MM string into a javascript Date object. I have tried new Date(string); and myDate.setTime() but to no avail.
A side question could be: How to convert a string in HH:MM into milliseconds from Jan 1, 1970.
Thanks for your help in advance.
How about something like:
//using timestr '10:33:21', could also be '10-33-21'
var dat = new Date, time = timestr.split(/\:|\-/g);
dat.setHours(time[0]);
dat.setMinutes(time[1]);
in JavaScript, I'm using the datejs library. http://www.datejs.com/
If you include this library, you have a function called "parseExact" and you could use it like this:
var dateString = "10-12";
var date = new Date.parseExact(dateString, "hh-mm");
To get the miliseconds, you can download the file time.js from http://code.google.com/p/datejs/source/browse/trunk/#trunk/src. Then you have a function getTotalMilliseconds() you can use:
var mSeconds = date.getTotalMilliseconds();
I hope this will help a little bit.