I was asking myself if there is an easy way to convert Moment.js (Javascript) (custom) time formats to Ruby/Rails DateTime formats, which also includes custom formats.
Example (Javascript Chrome Console):
var raw_string = "2017-02-28T01:28:27Z"
var my_custom_date_format = "YYYY-MM-DDTHH:mm:ssZ"
var parsed_string = moment(raw_string, my_custom_date_format)
console.log(parsed_string._f) # returns my_custom_date_format
I now want to send my_custom_date_format to Ruby/Rails and parse using:
IRB Console (Ruby):
require 'time'
time1 = Date.strptime("2017-02-28T01:28:27Z", "YYYY-MM-DDTHH:mm:ssZ") *
*✘ This would break because of another syntax.
time1 = Date.strptime("2017-02-28T01:28:27Z", "%Y-%m-%dT%H:%M:%SZ") **
** ✔This works, but I need a automatic converter of all possible js date formats to Ruby.
I was thinking of solving this issue maybe with RegEx, if possible or are there libraries able to convert this?
Thank you very much.
Related
I'm using Google Apps Script to retrieve some data through an API. The date that is given to me is a standard ISO 8601 string, and I need to convert that to a date number that will be understood by Google Sheets when I display it (i.e. as the Google Sheets / Excel standard date value)
Currently I'm using a workaround which is passing a string in my cells then converting it through the DATEVALUE() function but it is not optimal, since I cant use that function natively in my script (from my research on the topic).
I want to create a function directly in Google Apps script that converts the Javascript ol' Date() object into a readable value for my spreadsheet.
I've made a few attempts by converting the seconds since 1970 to the number of days since 1900 but I always have a two-hour gap that I can't explain. I suspect it has to do with the fact that I am in UTC+2, but can't really solve it, and adding two hours sounds like a bad fix.
The baseline of what I've gotten to so far is this :
function toDateNum(string) {
//Parsing to Unix Timestamp
date = new Date(string).getTime() / 1000
//Here I need convert to GSheets date value, add the number of days between 1900-01-01 and 1970-01-01
return date ;
}
I'm looking either for an arithmetic solve for this (converting and adding dates) or for a function integrated in the Google Sheets app that would allow me to work with this. Any suggestions ?
Thanks a lot !
EDIT (with additional clarification)
One of my issues is that the toISOString format returned is not supported by google sheets directly. It will only be read as a string, not as a date value. Currently, I'm working around this by sending the toISOString value in the cells and reformat using DateValue() directly in the table. I'm trying to do that natively in the script.
To the best of my knowledge, the date value supported by Google Sheets (and Excel) is the number of days since 1900-01-01. A simple arithmetic solution should be found (computing a unix timestamp from seconds then to days then add the difference between 1900-01-01 to 1970-01-01) but, then again, I get my two-hour gap that messes everything up.
You can achieve this by using new Date(string*1000), then passing the result to Utilities.formatDate(). Multiplying the Unix timestamp by 1000 means your argument is in milliseconds, rather than seconds. This Stackoverflow Question has a lot of good info for formatting dates using js.
function toDateNum(string) {
//convert unix timestamp to milliseconds rather than seconds
var d = new Date(string*1000);
//get timezone of spreadsheet
var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
//format date to readable format
var date = Utilities.formatDate(d, tz, 'dd-MM-yyyy hh:mm:ss a');
return date;
}
This script will use the timezone setting of your spreadsheet, but you can change this to use the time zone of the script or enter one yourself, examples below if you'd like to use these instead:
//use spreadsheet timezone setting
var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
//use script timezone setting
var tz = Session.getScriptTimeZone();
//enter your own time zone
var tz = 'GMT+0';
In the question linked below, the response by user79865 explains how to manage dates and their formats within sheets. The Sheets API documentation also specifies all the different formats you can use as well as how to create your own when working with dates and times. The Utilities.formatDate() will help you change the date format to whatever you need.
Question URL: https://webapps.stackexchange.com/questions/88621/basic-date-manipulation-in-google-script?newreg=7c66fdcf156f4ff5a30eb5fa4153b243
Sheets Documentation URL: https://developers.google.com/sheets/api/guides/formats
Im new to momentJs so I need a bit of help here. I am building a form where the user can send in their availabilities for a certain work period. So in the form you have a startDate, startTime, endDate and endTime. Due to the api that I have to use from a client we have to send the date like this (example) "2015-06-17T14:24:36" (with the 'T' in the middle). Currently I receive the date and the time seperate from eachother but merging them together in the end so it fits the api's way of reading date.
Now my question is as follow. I have to create a check where I can see if the input startdate-time and enddate-time are valid. For example the startdate always has to be a date BEFORE the end date (pretty logic right). But is there an easy way to do this in momentJS?
Or should I use another method?
Thanks in regard and if my question is not quite clear please let me know so I can provide extra information!
NOTE: in the end it should be something like this:
var start = "2017-06-17T14:24:36"
var end = "2017-07-03T14:24:36"
Function that checks if the start and end dates are valid
Result = true
If you simply have to check that startDate is before endDate you can use isAfter.
Here a working sample:
var start = "2017-06-17T14:24:36";
var end = "2017-07-03T14:24:36";
function checkDate(start, end){
var mStart = moment(start);
var mEnd = moment(end);
return mStart.isBefore(mEnd);
}
console.log(checkDate(start, end));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
In my first example I'm using moment(String) parsing that accepts input in ISO 8601 format.
If you need to parse non ISO 8601 format you can use moment(String, String) specifying input format (e.g. var mStart = moment(start, 'DD-MM-YYYYTHH:mm:ss');).
If you have to support multiple formats you can use moment(String, String[]). As docs states moment(String, String[]):
Prefer formats resulting in valid dates over invalid ones.
Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
Prefer formats earlier in the array than later.
I am trying to parse a date string i get from php through ajax call(which is irrelevant for now) using new Date().
however i keep getting wrong results.
My string is 2013-05-09 20:56:17
When i do
var something = new Date("2013-05-09 20:56:17");
alert(something.getMonth());
It keeps alerting 0
In my opinion for some reason new date cant parse this string.
Is there a way to specify the date format for new Date() in JS ?
My current solution is to import php's: date() and strtotime() and use them :
alert(date('m', strtotime("2013-05-09 20:56:17")));
This works however I have to use external js lib and I am pretty sure there is a better JS way to achieve that.
If you use slashes instead of hyphens, it works:
var something = new Date("2013/05/09 20:56:17");
alert(something.getMonth());
It's easy enough to replace any hyphens in a string with slashes first if you need to (say, if you were getting the date string from somewhere else):
var something = new Date("2013-05-09 20:56:17");
something = something.replace('-', '/');
It seems JavaScript's Date constructor doesn't recognize date formats with hyphens, or at least not that particular format.
Choose a different format specifier in PHP for your ajax dates. The format you expect and the format expected by the javascript are different.
var something = new Date("2013-05-09T20:56:17");
Note the 'T' which appears as a literal separator and marks the beginning of time per ISO 8601
Reference for various [browser] javascript date formats
W3 DateTime
Microsoft IE DateTime
Mozilla [Firefox] DateTime
Google DateJs
And lastly, the PHP date format specifier list:
PHP Date
PHP DateTime
Note the 'DATE_ISO8601'; but I suggest not using that at this time. Instead use 'DATE_ATOM' which may produce a date format more widely supported (comments suggest it makes iPhones happier and no issues with other browsers).
To use it in PHP:
$something = new DateTime('NOW');
echo $something->format('c');
echo $something->format(DateTime::ATOM);
im trying to convert a date format into a new format in this example is d/m/Y to Ymd, this is how i do it in PHP with DateTime::createFromFormat() is there a similer function in javascript to do this?
// 12/04/2012 work
// 12/4/2012 work
// 4/4/2012 work
// 04/4/2012 work
// 42/24/1234 not work
$date = DateTime::createFromFormat('d/m/Y', '12/04/2012');
$train_date = $date->format('Ymd'); change the format to // 20120412
in short how can i do this in javascript or nodejs?
It's nice to use external libraries since node.js has a philosophy of minimal core library.
Let's have a look at moment.js.
var moment = require('moment');
var date = moment('12/04/2012', 'DD/MM/YYYY');
var train_date = date.format('YYYYMMDD');
console.log(train_date);// 20120412
In the same spirit as discussed here, is there a recommended way to generate / parse dates from within a bash script so that it can be interfaced to Javascript Date?
To be precise, I get this strings when doing json encoding of a Javascript Date object:
2011-10-31T10:23:47.278Z
I could put together a bash hack to generate / parse that date format, but I would prefer to avoid reinventing the wheel. Does somebody have a working solution?
I am more interested in the "generating" side: I want to generate current dates from a bash script and save them in a json document (couchdb) so that they can be automatically ordered by the view engine.
The closest I am coming is this:
date -u +"%FT%T.000Z"
Which gives this output:
2011-11-03T06:43:08.000Z
I do not like that I have to put the T, the Z and the milliseconds to 0 manually (I can use %N for nanoseconds, and truncate with sed or whatever, but seems like overkill just to get millisecond precission), and I was hoping that there would be a built-in format token for date which would produce that UTC date. I assumed - wrongly it seems - that the format is common enough that it can be specified with just one format token.
JavaScript can convert many different values into dates. Not sure if that's what you mean, but for example. Your bash could generate this string: "2011/11/10 08:08:08"
When it gets to JavaScript land you can do this
var date = new Date("2011/11/10 08:08:08")
You can also do this:
var now = 1320287813362
var date = new Date(now)
More info on what Date accepts here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Other interesting info here:
What's the best way to store datetimes (timestamps) in CouchDB?