java 8 Nashorn engine not able to compare dates - javascript

I m suppose to compare two dates with Java 8 Nashorn engine. However it is not comparing dates correctly.
My Java Code:
Date start = new Date();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date end = cal.getTime();
engine.put("start", start); // engine is ScriptEngine
engine.put("end", end);
assertTrue((boolean)engine.eval("start < end")); //This assert is failing
//if I change dates to long it is working
engine.put("start", start.getTime());
engine.put("end", end.getTime());
assertTrue((boolean)engine.eval("start < end")); //This will now work
However I don't want to convert date to long because of some other requirements. Please suggest where I am making the mistake.
Thanks

In Nashnorn, new java.util.Date() and new Date() produce completely different objects. And it makes sense, since the functionality of either object differs a lot. Nashorn internally uses jdk.nashorn.internal.objects.NativeDate.
The later, native JS, can be safely compared with < and >. For the former, the comparison will be purely by address in memory.
To work with less and greater operators, I recommend to convert Java dates to NativeDate when populating engine's global context.
One possible way of doing it would be
Date start = new Date();
ScriptObjectMirror jsDate = (ScriptObjectMirror) engine.eval("new Date();")
jsDate.callMember("setTime",start.getTime());
engine.put("start", jsDate);
engine.eval("print(start.constructor + ':' + start)");
Prints "function Date() { [native code] }:Sat Jul 23 2016 19:05:53 GMT-0400 (EDT)"
However
engine.put("javaStart", new Date());
engine.eval("print(javaStart.constructor + ':' + javaStart)");
prints "undefined:Sat Jul 23 19:05:53 EDT 2016"

Related

Jquery countdown in UTC [duplicate]

Suppose a user of your website enters a date range.
2009-1-1 to 2009-1-3
You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC.
Now suppose the user is in Alaska. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?
Simple and stupid
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(),
date.getUTCMinutes(), date.getUTCSeconds());
console.log(new Date(now_utc));
console.log(date.toISOString());
The toISOString() method returns a string in simplified extended ISO
format (ISO 8601), which is always 24 or 27 characters long
(YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ,
respectively). The timezone is always zero UTC offset, as denoted by
the suffix "Z".
Source: MDN web docs
The format you need is created with the .toISOString() method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:
This will give you the ability to do what you need:
var isoDateString = new Date().toISOString();
console.log(isoDateString);
For Timezone work, moment.js and moment.js timezone are really invaluable tools...especially for navigating timezones between client and server javascript.
Here's my method:
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
The resulting utc object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.
Update: This answer is a quick-and-dirty way to get the UTC date when calling utc.toString(), utc.toLocaleString(), etc. Though, there are better solutions, in particular nowadays with modern browsers, and I should work on an improved answer. Basically, now.toISOString() (IE 9+) is what you want to use.
Convert to ISO without changing date/time
var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time)
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z
Convert to ISO with change in date/time(date/time will be changed)
isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z
Fiddle link
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
Another solution to convert to UTC and keep it as a date object:
(It works by removing the ' GMT' part from the end of the formatted string, then putting it back into the Date constructor)
const now = new Date();
const now_utc = new Date(now.toUTCString().slice(0, -4));
console.log(now_utc.toString()); // ignore the timezone
I needed to do this to interface with a datetime picker library. But in general it's a bad idea to work with dates this way.
Users generally want to work with datetimes in their local time, so you either update the server side code to parse datetime strings with offsets correctly, then convert to UTC (best option) or you convert to a UTC string client-side before sending to the server (like in Will Stern's answer)
Browsers may differ, and you should also remember to not trust any info generated by the client, that being said, the below statement works for me (Google Chrome v24 on Mac OS X 10.8.2)
var utcDate = new Date(new Date().getTime());
edit: "How is this different than just new Date()?" see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments. (note: Date.UTC() returns the number of millisecond since 1970-01-01 00:00:00 UTC)
Adding the 60000 * Date.getTimezoneOffset() as previous answers have stated is incorrect. First, you must think of all Dates/Times as already being UTC with a timezone modifier for display purposes.
Again, browsers may differ, however, Date.getTime() returns the number of milliseconds since 1970-01-01 UTC/GMT. If you create a new Date using this number as I do above, it will be UTC/GMT. However, if you display it by calling .toString() it will appear to be in your local timezone because .toString() uses your local timezone, not the timezone of the Date object it is called on.
I have also found that if you call .getTimezoneOffset() on a date, it will return your local timezone, not the timezone of the date object you called it on (I can't verify this to be standard however).
In my browser, adding 60000 * Date.getTimezoneOffset() creates a DateTime that is not UTC. However when displayed within my browser (ex: .toString() ), it displays a DateTime in my local timezone that would be correct UTC time if timezone info is ignored.
My solution keeps the date the same no matter what timezone is set on the client-side. Maybe someone will find it useful.
My use case:
I'm creating a todo app, where you set date of your task. This date should remain constant no matter what timezone you're in.
Example. You want to call your friend at 8 am on June 25th.
You create this task 5 days before (June 20th) while you're in China.
Then, on the same day, you fly to New York for a few days.
Then on June 25th, while you're still in New York, you wake up at 7:30 am (which means you should receive task notification in 30 mins (even tho it's 1:30 pm already in China where you were when creating the task)
So the task is ignoring the timezone. It means 'I want to do it at 8 am in whatever timezone I'll be in'.
What I do is let's say 'I assume you're always in London Timezone - UTC'.
What it means is - when the user picks some date in her/his Timezone - I convert this date to the same date in UTC. ie. You pick 8 am in China, but I convert it to 8 am in UTC.
Then - next time you open the app - I read the date saved in UTC and convert it to the same date in your current timezone - eg. I convert 8 am in UTC to 8 am in the New York timezone.
This solution means that the date can mean something else depending on where you are when setting it and where you're reading it, but it remains constant in a way that it 'feels' like you're always in the same timezone.
Let's write some code:
First - we have 2 main functions for converting from/to UTC ignoring timezone:
export function convertLocalDateToUTCIgnoringTimezone(date: Date) {
const timestamp = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
);
return new Date(timestamp);
}
export function convertUTCToLocalDateIgnoringTimezone(utcDate: Date) {
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate(),
utcDate.getUTCHours(),
utcDate.getUTCMinutes(),
utcDate.getUTCSeconds(),
utcDate.getUTCMilliseconds(),
);
}
Then, I save/read this date like:
function saveTaskDate(localDate: Date) {
// I convert your local calendar date so it looks like you've picked it being in UTC somewhere around London
const utcDate = convertLocalDateToUTCIgnoringTimezone(localDate);
api.saveTaskDate(utcDate);
}
function readTaskDate(taskUtcDate: Date) {
// I convert this UTC date to 'look in your local timezone' as if you were now in UTC somewhere around london
const localDateWithSameDayAsUTC = convertUTCToLocalDateIgnoringTimezone(taskUtcDate);
// this date will have the same calendar day as the one you've picked previously
// no matter where you were saving it and where you are now
}
var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();
Are you trying to convert the date into a string like that?
I'd make a function to do that, and, though it's slightly controversial, add it to the Date prototype. If you're not comfortable with doing that, then you can put it as a standalone function, passing the date as a parameter.
Date.prototype.getISOString = function() {
var zone = '', temp = -this.getTimezoneOffset() / 60 * 100;
if (temp >= 0) zone += "+";
zone += (Math.abs(temp) < 100 ? "00" : (Math.abs(temp) < 1000 ? "0" : "")) + temp;
// "2009-6-4T14:7:32+10:00"
return this.getFullYear() // 2009
+ "-"
+ (this.getMonth() + 1) // 6
+ "-"
+ this.getDate() // 4
+ "T"
+ this.getHours() // 14
+ ":"
+ this.getMinutes() // 7
+ ":"
+ this.getSeconds() // 32
+ zone.substr(0, 3) // +10
+ ":"
+ String(temp).substr(-2) // 00
;
};
If you needed it in UTC time, just replace all the get* functions with getUTC*, eg: getUTCFullYear, getUTCMonth, getUTCHours... and then just add "+00:00" at the end instead of the user's timezone offset.
date = '2012-07-28'; stringdate = new Date(date).toISOString();
ought to work in most newer browsers. it returns 2012-07-28T00:00:00.000Z on Firefox 6.0
My recommendation when working with dates is to parse the date into individual fields from user input. You can use it as a full string, but you are playing with fire.
JavaScript can treat two equal dates in different formats differently.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Never do anything like:
new Date('date as text');
Once you have your date parsed into its individual fields from user input, create a date object. Once the date object is created convert it to UTC by adding the time zone offset. I can't stress how important it is to use the offset from the date object due to DST (that's another discussion however to show why).
var year = getFullYear('date as text');
var month = getMonth('date as text');
var dayOfMonth = getDate('date as text');
var date = new Date(year, month, dayOfMonth);
var offsetInMs = ((date.getTimezoneOffset() * 60) // Seconds
* 1000); // Milliseconds
var utcDate = new Date(date.getTime + offsetInMs);
Now you can pass the date to the server in UTC time. Again I would highly recommend against using any date strings. Either pass it to the server broken down to the lowest granularity you need e.g. year, month, day, minute or as a value like milliseconds from the unix epoch.
If you are dealing with dates a lot, it's worth using moment.js (http://momentjs.com). The method to convert to UTC would be:
moment(yourTime).utc()
You can use format to change your date to any format you want:
moment(yourTime).utc().format("YYYY-MM-DD")
There is offset options in moment as well but there is an additional complementary library for dealing with timezone (http://momentjs.com/timezone/). The time conversion would be as simple as this:
moment.tz(yourUTCTime, "America/New_York")
I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.
You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:
$.parseDate('yy-mm-dd', '2007-01-26');
I just discovered that the 1.2.3 version of Steven Levithan's date.format.js does just what I want. It allows you to supply a format string for a JavaScript date and will convert from local time to UTC. Here's the code I'm using now:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
Using moment.js UTC method;
const moment = require('moment');
const utc = moment.utc(new Date(string));
This function works beautifully for me.
function ParseDateForSave(dateValue) {
// create a new date object
var newDate = new Date(parseInt(dateValue.substr(6)));
// return the UTC version of the date
return newDate.toISOString();
}
This method will give you : 2017-08-04T11:15:00.000+04:30 and you can ignore zone variable to simply get 2017-08-04T11:15:00.000.
function getLocalIsoDateTime(dtString) {
if(dtString == "")
return "";
var offset = new Date().getTimezoneOffset();
var localISOTime = (new Date(new Date(dtString) - offset * 60000 /*offset in milliseconds*/)).toISOString().slice(0,-1);
//Next two lines can be removed if zone isn't needed.
var absO = Math.abs(offset);
var zone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(absO / 60)).slice(-2) + ":" + ("00" + (absO % 60)).slice(-2);
return localISOTime + zone;
}
If you need Date Object
Passing only date string Date assumes time to be 00:00 shifted by time zone:
new Date('2019-03-11')
Sun Mar 10 2019 18:00:00 GMT-0600 (Central Standard Time)
If you add current hours and minutes you get proper date:
new Date('2019-03-11 ' + new Date().getHours() + ':' + new Date().getMinutes())
Mon Mar 11 2019 04:36:00 GMT-0600 (Central Standard Time)
The getTimezoneOffset() method returns the time zone difference, in
minutes, from current locale (host system settings) to UTC.
Source: MDN web docs
This means that the offset is positive if the local timezone is behind UTC, and negative if it is ahead. For example, for time zone UTC+02:00, -120 will be returned.
let d = new Date();
console.log(d);
d.setTime(d.getTime() + (d.getTimezoneOffset() * 60000));
console.log(d);
NOTE: This will shift the date object time to UTC±00:00 and not convert its timezone so the date object timezone will still the same but the value will be in UTC±00:00.
This is what I have done in the past:
var utcDateString = new Date(new Date().toUTCString()).toISOString();
For other people whos goal is to get it as a "Date Object" and not as a string, and you only want to display the date/time without the TZ (probably hardcoded), what you can do is:
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();
const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);
// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.
You can then do stuff like:
We will delete your account at ${format(tomorrowUTC, 'EEEE do MMMM hh:mmaaa')} UTC
(format is a date-fns function, you can use other lib if you want);
This is kinda "hacky" as this is still using your local timezone, but if you just wanna display the date and not the timezone, then this works.
If your date has the timezone on it you can use date-fns-tz:
import { zonedTimeToUtc } from 'date-fns-tz';
const dateBrazil = new Date() // I'm in Brazil, you should have or get the user timezone.
const dateUtc = zonedTimeToUtc(dateBrazil, 'America/Sao_Paulo')
Looking at your question its clear that you just want to send the date range to your backend for further post processing.
I am assuming you are conforming to the standard data guidelines which expect the data to be in a particular format. For example, I use ODATA which is a RESTfull API which expects date time objects to be in the format:-
YYYY-MM-DDT00:00:00.
That can be easily achieved via the snippet posted below(Please change the format as per your requirement).
var mydate;//assuming this is my date object which I want to expose
var UTCDateStr = mydate.getUTCFullYear() + "-" + mydate.getUTCMonth() + "-" + mydate.getUTCDate() + "T00:00:00";
If on the other hand, you are in my situation wherein you have received a date from your backend, and the browser converts that to your local date. You on the other hand are interested in the UTC date then you can perform the following:-
var mydate;//assuming this is my date object which I want to expose
var UTCDate = new Date(mydate);/*create a copy of your date object. Only needed if you for some reason need the original local date*/
UTCDate.setTime(UTCDate.getTime() + UTCDate.getTimezoneOffset() * 60 * 1000);
The code snippet above basically adds/subtracts the time added/subtracted by the browser based on the timezone.
For example if I am in EST(GMT-5) and my Service returns a date time object = Wed Aug 17 2016 00:00:00 GMT-0500
my browser automatically subtracts the timezone offset(5hrs) to get my local time. So if I try to fetch the time I get Wed Aug 16 2016 19:00:00 GMT-0500. This causes a lot of problems. There are a lot of libraries out there which will definitely make this easier but I wanted to share the pure JS approach.
For more info please have a look at: http://praveenlobo.com/blog/how-to-convert-javascript-local-date-to-utc-and-utc-to-local-date/ where in I got my inspiration.
Hope this helps!
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
This will give you the proper UTC Date and Time.
It's because the getTimezoneOffset() will give you the timezone difference in minutes.
I recommend you that not to use toISOString() because the output will be in the string Hence in future you will not able to manipulate the date
Using moment package, you can easily convert a date string of UTC to a new Date object:
const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();
This specially helps when your server do not support timezone and you want to store UTC date always in server and get it back as a new Date object. Above code worked for my requirement of similar issue that this thread is for. Sharing here so that it can help others. I do not see exactly above solution in any answer. Thanks.
I know this question is old, but was looking at this same issue, and one option would be to send date.valueOf() to the server instead. the valueOf() function of the javascript Date sends the number of milliseconds since midnight January 1, 1970 UTC.
valueOf()
You can use the following method to convert any js date to UTC:
let date = new Date(YOUR_DATE).toISOString()
// It would give the date in format "2020-06-16T12:30:00.000Z" where Part before T is date in YYYY-MM-DD format, part after T is time in format HH:MM:SS and Z stands for UTC - Zero hour offset
By far the best way I found to get the GMT time is first get your local date time. Then convert in to GMT String. Then use the string to build new time by removing the timezone.
let dtLocal = new Date()
let dt = new Date(dtLocal.toISOString().split('Z')[0])
Note: - it will create the new datetime in GMT. But it will be local date time as timezone will be attached to it.
Extension function:
if (!Date.prototype.toUTC){
Date.prototype.toUTC = function(){
var utcOffset = new Date().getTimezoneOffset();
var utcNow = new Date().addMinutes(utcOffset);
return utcNow;
};
}
Usage:
new Date().toUTC();

Comparison of object and number in JS [duplicate]

Let's assume I have a proper Date object constructed from the string: "Tue Jan 12 21:33:28 +0000 2010".
var dateString = "Tue Jan 12 21:33:28 +0000 2010";
var twitterDate = new Date(dateString);
Then I use the < and > less than and greater than comparison operators to see if it's more or less recent than a similarly constructed Date. Is the algorithm for comparing dates using those operators specified, or is it specifically unspecified, like localeCompare? In other words, am I guaranteed to get a more recent date, this way?
var now = new Date();
if (now < twitterDate) {
// the date is in the future
}
Relational operations on objects in ECMAScript rely on the internal ToPrimitive function (with hint number) that you can access, when it is defined, using valueOf.
Try
var val = new Date().valueOf();
You'll get the internal value of the date which is, as in many languages, the number of milliseconds since midnight Jan 1, 1970 UTC (the same that you would get using getTime()).
This means that you're, by design, ensured to always have the date comparison correctly working.
This article will give you more details about toPrimitive (but nothing relative to comparison).
Date values in Javascript are numbers, as stated in the ECMA Script specification. So the Date values are compared as numbers.
This is a demo of your code (I set twitterDate in the future).
(function(){
var dateString = "Tue Jan 12 21:33:28 +0000 2014";
var twitterDate = new Date(dateString);
var now = new Date();
if (now < twitterDate) {
document.write('twitterDate is in the future');
}
else
{
document.write('twitterDate is NOT in the future');
}
})()​
I think yes. Using if (now < twitterDate), it evaluates to if (now.valueOf()<twitterDate.valueOf()). valueOf() delivers the number of milliseconds passed since 01/01/1970 00:00:00, so the comparison of those 2 numbers is valid.
check it like this
var then = new Date("Tue Jan 12 21:33:28 +0000 2010")
,now = new Date;
console.log(then.valueOf(),'::',now.valueOf(),'::',now<then);
//=> 1263332008000 :: 1352365105901 :: false

Javascript method Date() is returning wrong date (Feb 9 instead of Sep 2) on my system,

I have a JavaScript method which gets current date and returns its universal time. Below is the code:
function calUTCTime(offset) {
var currentDate = new Date();
var utc = currentDate.getTime() - (currentDate.getTimezoneOffset() * 60000);
var result = new Date(utc + (3600000 * offset));
return result .toLocaleString();
}
Above code is returning wrong date, it is replacing date with month and date format in my system is dd-MM-yyyy, OS is Windows 8. I tried on other system's and the date is correct but on my system it is wrong. Please share suggestions.
That is exactly what I would expect from .toLocaleString(). The browser is determining your language (or "locale") from the OS and using it to choose how to output the string. If you want a generic human-readable date format, try a simple .toString() instead.
If you want complete and total control over how a date is formatted, try a library like moment.js. For example, your above code could be condensed to:
return moment().utc().format("YYYY-MM-DD"); // "2014-09-02"
There is another post that summarizes the differences between the two methods: JavaScript: Difference between toString() and toLocaleString() methods of Date

Getting next day date for specific string format in Google Apps Script (JavaScript)

Good day everyone!
Working on aprojectmI had to start working with Google Spereadsheet interface and faced a problem I cannot quickly overcome due to not working with JavaScripts ever before.
I have a date in specific format as a string
var date = "2012-08-09";
What I need is to get the next day date as
date = "2012-08-10";
which should include changing not only the day, but month and year too, if necessary.
I've tried using date format
var datum= new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.toString('yyyy-MM-dd');
but the code appears to fail at writing date to datum variable.
What is the best and quickiest way tosolve this litle problem?
Thanks
The problem when you tag a question 'Javascript' and when you are actually using Google Apps Script is that you get nice answers from people that do not know some special functions available in GAS.
GAS is based on Javascript but Javascript is not GAS... if you see what I mean ;-)
That said, there is actually a "special" function to format date string and I'll show it in the following code.
But there is also another point that could put you into trouble : if you don't mention hours in your date object there is a risk to shift one day if you live in a country that uses daylight savings. This issue has been discussed quite often on this forum and elsewhere so I won't give all the details but it's a good idea to take this into account when you play with date objects. In the code below I extract a tz (time zone) string from the date object we have just created to know if it's in summer or in winter time, then I use this tz string as a parameter in the Utilities.formatDate() method . This guarantees an exact result in every situations.
Here is (finally) the test code :
(use the logger to see results. script editor>view>logs)
function test(){
date = "2012-08-9";
var parts = date.split('-')
var datum = new Date(parts[0],parts[1]-1,parts[2],0,0,0,0);// set hours, min, sec & milliSec to 0
var tz = new Date(datum).toString().substr(25,8);// get the tz string
Logger.log(datum+' in TimeZone '+tz)
datum.setDate(datum.getDate() + 1);// add 1 day
var dateString = Utilities.formatDate(datum,tz,'yyyy-MMM-dd');// show result like you want, see doc for details
Logger.log(dateString);// the day after !
}
Logger results :
Thu Aug 09 2012 00:00:00 GMT+0200 (CEST) in TimeZone GMT+0200
2012-Aug-10
It sounds like a parsing problem you may have better luck, splitting out the date and putting the parameters in individually, any errors you get would be useful:-
var parts = date.split("-");
var datum = new Date(
parseInt(parts[0], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[2], 10));
There is no built in formatting function for the JavaScript Date object, I'm not sure if the google apps api is any different though. To perform the last line of your code you may either need to write your own functions to extract the data from the JavaScript date object and format it, hint you will also need to write a zerofill function if you want to ensure two digits in your date and month parts of the output.
var formatted = datum.getFullYear() + "-" +
zerofill(datum.getMonth() + 1, 2) + "-" +
zerofill(datum.getDate(), 2);
Passing a format string to toString works in .NET, and it may work in Java, however this doesn't work in Javascript.
Try the following,
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
Try the following in http://jsfiddle.net/ It works.....
<html>
<head>
<script>
function foo(){
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
document.getElementById("demo").innerHTML = date;
}
</script>
</head>
<body onload="foo()">
<p id=demo></p>
</body>
</html>​

Javascript date parsing on Iphone

I'm working on an offline capabable Javascript site that targets mobile devices. One such mobile device is the IPhone.
I'm trying to parse a date from our REST API (a member of JSON object). I'm using
Date.parse("2010-03-15 10:30:00");
This works on Android devices, however on IPhone it just gives an invalid date.
How do I need to format my date string so it can be parsed by the IPhone?
Not all browsers support the same date formats. The best approach is to split the string on the separator characters (-, and :) instead, and pass each of the resulting array items to the Date constructor:
var arr = "2010-03-15 10:30:00".split(/[- :]/),
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
console.log(date);
//-> Mon Mar 15 2010 10:30:00 GMT+0000 (GMT Standard Time)
This will work the same in all browsers.
For UTC/GMT time, you can try:
var arr = "2014-10-27T16:05:44+0000".split(/[\-\+ :T]/);
var date = new Date();
date.setUTCFullYear(arr[0]);
date.setUTCMonth(arr[1] - 1);
date.setUTCDate(arr[2]);
date.setUTCHours(arr[3]);
date.setUTCMinutes(arr[4]);
date.setUTCSeconds(arr[5]);
The date object will display in the proper local timezone when used.
You might have better luck if you stick to ISO 8601 format:
Date.parse("2010-03-15T10:30:00");
// e.g.
var d = new Date( Date.parse("2010-03-15T10:30:00") );
console.log( d.toString() ); //Mon Mar 15 2010 10:30:00 GMT+0000 (BST)
Update 2019-07-29: Not removing existing content below, but I highly suggest you don't use this method. I learned from my mistakes. Do not override JavaScript's existing methods. Becomes bad for your code's portability and performance. If you can't get ISO 8601 (which is standard practice in JS and most API's) - then change that system instead. Alternatively, write your own function, which always has to be called to generate a Date object.
If you can correct your REST API to send down proper ISO 8601 date times, the proper way to handle this is to use a regex shim that allows all browsers to process ISO 8601 dates. Sure it might be slower, but handling dates with Javascript is like trying to get a cat into a tub of water.
Keep in mind the following method overrides the original Date.parse method. This could be problematic in larger projects or with many developers with different expectations. Use only if you're aware of what you're doing.
/**
* Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
* © 2011 Colin Snover <http://zetafleet.com>
* Released under MIT license.
*/
(function (Date, undefined) {
var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
Date.parse = function (date) {
var timestamp, struct, minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; (k = numericKeys[i]); ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
}
else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
}(Date));
https://github.com/csnover/js-iso8601
There is bug in the
var date = new Date();
date.setUTCFullYear(arr[0]);
date.setUTCMonth(arr[1] - 1);
date.setUTCDate(arr[2]);
date.setUTCHours(arr[3]);
date.setUTCMinutes(arr[4]);
date.setUTCSeconds(arr[5]);
approach. If Date() is the end of month and the month set has less days then the result is one month out.
Wrapping Up with the string will do the magic. Since the safari has some unique way of parsing and formatting date
Date.parse(String("2010-03-15 10:30:00"));
Still facing issue use the Moment.js
Happy to help. :-)

Categories

Resources