Convert JavaScript date() to Python Django models.DateTimeField - javascript

I using django model forms to submit data to the database.
I use JavaScript to auto-fill the form with the following
document.getElementById('id_date_received').value = Date();
This outputs: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT)
while django's models.DateTimeField expects: 2017-02-06 11:39
How do i convert: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT) to 2017-02-06 11:39
Thanks

IMO, the best solution would be using unix timestamps, because you can avoid all complex stuff connected with timezones and time parsing.
JS:
js_date = new Date('2012.08.10');
// getTime() returns milliseconds from the UNIX epoch,
// so divide it by 1000 to get the seconds representation.
js_timestamp = js_date.getTime() / 1000;
Python:
python_date = datetime.datetime.fromtimestamp(js_timestamp)

You should consider use Moment.js, it's the easiest javascript library to manipulate dates and timezone formats.
So the code would by something like this:
moment(YOUR_DATE_VARIABLE).format('YYYY-MM-DD HH:mm'); // 2017-02-06 11:39
Hope this help you.

You can set the pattern of date in your model form that accept particular format.
input_formats=[list of datetime patterns that you want to accept]

This is a bit of a long-winded solution but this should work to convert Date to django date time
I first convert the Date to a string by cast
(String(date_var))
then when I receive the API call I convert it using this command
datetime.datetime.strptime(",".join(original_time[:original_time.find("(")-1].split(" ")).replace("GMT",""), '%a,%B,%d,%Y,%H:%M:%S,%z')
I would recommend preserving the timezone as different servers can be in different timezones which can screw up your dates!

Related

How do I deal with dates-only in javascript when it keeps appending a time value?

I have a bunch of date fields (not datetime) in SQL Server. When they are fetched by the web server and sent to the client as JSON a time stamp is appended automatically. So instead of receiving just 2016-09-27 I get 2016-09-27T00:00:00.
When the user interacts with the uiBootstrap calendar control it automatically parses that string into a javascript date object and applies a 4 hour offset for the timezone. When this is sent back to the server it's sent as 2016-09-26T20:00:00. Now my date is off by a day. Also the next time it's fetched it will happen again. But this time it will start at 2016-09-26T00:00:00 and will roll back to 2016-09-25T20:00:00. Each cycle between client and server loses a day.
How do I keep my dates from changing? I'm looking at moment.js but so far haven't really figured out how it can help me.
EDIT
I've setup a test function to try different methods of converting datetimes back and forth.
console.log('JSONDate: ' + JSONDate);
var dt = new Date(JSONDate);
console.log('JS Converted Date: ');
console.log(dt);
console.log('Date converted back to string: ' + dt.toISOString());
Here's the output:
JSONDate: 2016-10-02T00:00:00
JS Converted Date: Sun Oct 02 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
Date converted back to string: 2016-10-02T04:00:00.000Z
In this example the date is now 4 hours ahead.
EDIT 2
Web server is running .net, specifically WebAPI 2. I'm using Entity Framework 6 to communicate between web server and SQL Server 2012.
Ideally, your dates would be serialized in the JSON as just dates. Instead of 2016-10-02T00:00:00, you'd have 2016-10-02. The problem is that .NET doesn't have a built in Date type. It only has DateTime. There are alternatives, such as LocalDate in Noda Time, as discussed in this answer.
However, assuming you don't want to change anything on the back-end, the way to handle this is just to make sure the input date/time is treated as local time, and never converted to/from UTC. This should be the default behavior when you parse the string into a Date object when the string is like 2016-10-02T00:00:00, but the behavior has changed a few times over the years, so if you are potentially dealing with older browsers, you may get some that interpret it as UTC instead.
As far as output goes, the toISOString method of the Date object always outputs in UTC - which is the source of your conversion error. If you want an ISO8601 string in local time - you'd have to construct one yourself using the various accessor functions (getFullYear, etc.), handling zero-padding, and ensuring months are incremented to be 1-based instead of 0-based.
The easier solution is to use moment.js, which can handle this for you.
var d = moment('2016-10-02T00:00:00').toDate(); // now you have a `Date` object
var s = moment(d).format("YYYY-MM-DD[T]HH:mm:ss"); // now you have a string again
Of course, if you don't need the time portion, you can omit it from the format string and the rest should still work out ok.
You could try getting the offset and applying it back to the date. Something like this:
var d = new Date('2016-09-27'); //Mon Sep 26 2016 20:00:00 GMT-0400 (EDT)
new Date(d.getTime() + d.getTimezoneOffset() * 60 * 1000) //Tue Sep 27 2016 00:00:00 GMT-0400 (EDT)

Date is in string format

I am a newbie in javascript, come to my question.
I am using ionic 2 build application in which i am using date time picker for taking a time.
I am getting a a time format is in the "hh:mm" using time picker. eg(10:11) which is in string format and i am using Date() function which give me date is in something like
"Mon Aug 01 2016 01:32:03 GMT-0700 (Pacific Daylight Time)"
I want to replace "hh:mm"(01:32) from Date object with my string output of "hh:mm"(10:11) and then want to convert that into new Date object.
I also tried split and slice function but doesn't work.
If i get some guide about this will be very helpful.
I will be very helpful to all of you.
thanks
First of all, read up on Date.
In your case, the following code is a starting point.
var d = new Date();
d.setHours('10');
d.setMinutes('11');
Of course, you should exchange '10' and '11' with your picker data. Also, there are many other methods you can use on the Date object.

JavaScript change timezone

Hello I am using Twitter REST API to call the home_timeline for timelines.
But I found that the object it returned had the created_at with GMT+0 timezone, how can I adjust the timezone to the user's local timezone for example GMT+8?
Here is the original data with GMT+0 from Twitter API:
Wed May 04 16:23:13 +0000 2016
what's the expected output format?
you can try:
var d = new Date('Wed May 04 16:23:13 +0000 2016');
var localeTime = d.toLocaleString();
console.log(localeTime);
if you expect a specific output format, you can use http://momentjs.com/timezone/ , to change both the timezone and format
I'm highly recommend to use MomentJS timezone library.
Furthermore, I'm recommend not to use GMT+8 label for time shifting, and use, for example, "Asia/Shanghai" instead. I would save hours to debug for you.
So, code barebone look like:
let moment = require("moment-timezone");
moment("Wed May 04 16:23:13 +0000 2016").tz("Asia/Shanghai").format('YYYYMMDD hh:mm:ss')
Output would be something like "20160505 12:23:13".
Thanks!

Json stringify changes dates

Hello I have an object in js with a field date. I try to stringify it at an ajax request but the result is inconsistent. After stringify the new object is one day earlier.
To be more specific this is the code on my file:
console.log(reservation.checkin);
console.log( JSON.stringify(reservation.checkin));
And this is the outcome:
Thu Jan 01 2015 00:00:00 GMT+0200 (EET)
"2014-12-31T22:00:00.000Z"
Am I doing something wrong? Is that output what it should be? Thx in advance!
edit: From an answer below it seems that it is at different timezone. What is the correct way to stringify this date?
It's not changing the date, just showing it in another timezone (UTC / GMT)
GMT+0200 (EET) means 2 hours differenece with UTC / GMT
so that's exaclty what you see in the result.
it depends a bit on the purpose. If you want ot post this in another API, it should work fine (presuming, the api uses timezone standards), in case you want to just show it in a gui... why use the json stringify...
I am not going to do all the math for you, i suggest you know why now, so just google: 'javascript format timezone' or something like that.
e.g:
Convert date to another timezone in JavaScript
Well, it is timezone - your date is GMT +2:00,
and after applying Stringify you get UTC.
You may want to check Date method .getTimezoneOffset() and maybe update the date
JSON.stringify is calling Date.toJSON() to convert the date.
See The "right" JSON date format.

Invalid date/None showing up for JS Date object in IE/Firefox

I am displaying a date time object in a table however for some reason in IE it display as None or Invalid Date is there something wrong with my format or is there an easy way for making this more readable such as mm/dd/yyyy HH:MM
this is what displays in chrome:
Mon Nov 28 2011 16:00:00 GMT-0500 (EST)
This is being converted from a Unix timestamp to that output in an API layer.
Probably the creation of the Date object fails, because the new Date() constructor accepts just some limited, implementation-dependent set of date strings.
You can use the Globalize library to deal with such issues, even if no localization in the usual sense is involved—but dealing with different string presentations of dates as is localization of a kind. It first looks a bit messy (it takes some time to dig into it—my book “Going Global with JavaScript and Globalize.js” contains a more readable description of it, with many examples), and it’s far from perfect, but it’s very useful.
If you know that your timestamp data is of some known exact format, you can parse it easily and then output it according to your own format descriptor. Assuming, for the sake of definiteness, that the format is the one exemplified with
Mon Nov 28 2011 16:00:00 GMT-0500 (EST)
(I know it’s an output format you mentioned, but I just use it as an example), you would first do simple string operation to discard the “GMT” and “(EST)” part (Globalize cannot currently handle them), producing e.g.
Mon Nov 28 2011 16:00:00 -05:00
and then you would just use code like the following:
var foo = Globalize.parseDate(timestamp,'ddd MMM d yyyy HH:mm:ss zzz');
var out = Globalize.format(foo,'MM/dd/yyyy HH:MM');
document.write(out);
just make your own method to format the date as string so you pass all problems with diffrent browsers and plateforms
I suspect Chrome is being helpful here and calling the .toString() method for you.
The Date object has several methods for formatting string output. See the w3schools reference page for examples.

Categories

Resources