I want to update a date linked by ngModel, using ngx-bootstrap datepicker, then send it in a PUT request to my Django backend. But the date format keeps getting changed from YYYY-MM-DD (2019-08-13) to the full javascript datestring (2019-08-13T23:00:00.000Z) which wont let me send the PUT request then.
I have tried nearly everything I can find on all other problems and it just doesnt work, nothing will let me select it as YYYY-MM-DD and keep it that way in the PUT request. Any help greatly appreciated.
<input class="form-control"
#dp="bsDatepicker"
bsDatepicker
[(ngModel)]="project.Start_Date2"
name="Start_Date2"
[bsConfig]="{
dateInputFormat: 'YYYY-MM-DD',
isAnimated: true,
containerClass: 'theme-default'
}">
I just want to be able to send my PUT request with the date format as YYYY-MM-DD. I am not sure if ngx-bootstrap will do it because when I pick a date with it, it converts it to the long string which then doesn't work in the PUT request.
The reason the date format keeps getting reverted is precisely because you use the ngModel, ie. two-way binding. The ngx-datepicker keeps pushing the selected value to your bound variable (Start_Date2). That is alright and expected.
I don't know how you do your PUT request, but you're going to need to do your format conversion either on the fly inside the request function or introduce another variable which will hold your date with the desired format.
I assume you use the angular HttpClient and the put request looks something like
this.http.put('https://example.com/dates/1', project.Start_Date2)
So what you can do is create a conversion function and convert the format inside the put call.
function myDateFormatFunction(inputDate) {
let d = new Date(inputDate) // this might not be needed if the date is already a Date() object
// YYYY-MM-DD
return d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); // the zeroes and slice weirdness is to have nice padding, borrowed from https://stackoverflow.com/a/3605248/3158815
}
this.http.put('https://example.com/dates/1', myDateFormatFunction(project.Start_Date2))
Related
I must be missing something very obvious, but I could use help. I have an Angular web app, which is getting data from a MS Web API. The DTO object has two date fields. When those fields come in, there is a "T" in the date field.
e.g. 2017-05-01T03:43:55
For whatever reason, I can't seem to get rid of that darn "T" when using the date. I'd tried using a date format both on the calendar control that displays the date data, and using the JavaScript format() command. I also tried using the Javascript replace() command to replace the "T" with a space. And I tried using Moment.js to create a new date (which seems to fail and give me an invalid date).
var startDate = moment(badge.startDate).format('yyyy-MM-dd HH:mm:ss');
var startDate = badge.startDate.format(''yyyy-MM-dd HH:mm:ss'');
var startDate = moment(badge.startDate).replace('T',' ');
What am I missing? How should I be doing this? As far as I can tell, any of these should work?
You can create separate filter for that as below.
return (input) ? $filter('date')("2017-05-01T03:43:55", "yyyy-MM-dd HH:mm:ss") : '';
You can change for of date according to your requirements. You can see details Below.
https://docs.angularjs.org/api/ng/filter/date
use, don't build what already exists!
First visit moment js this component is very helpful and has many options which you can do with a date.
var date = moment(yourDate).format('YYYY-MM-DD');
format has a lot of options, you can find it on moment js documents.
Similar questions has been asked many times but I couldn't find a more concrete solution. The things I'm doing are:
I have a <input type="date"> inside my HTML which when clicked opens a calender with date in dd/mm/yyyy format.
I change the html5 date to timestamp to send to my db by Date.parse(html5Date) and in the server I modify the date and send it back to my Angular app.
I now convert the timestamp back to Date object by new Date(timestamp).To print the date in a human-friendly format inside a table I do [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/').
On edit (PUT request), I again capture the date from HTML, convert it to timestamp, send it to server and process the returning date back to html date.
Other than these, I also do a ton of functionalities like date comparison, adding hours to the dates, show time of the day etc inside the HTML:
Just these simple operations are over 120 lines of code which I think is ridiculous and error prone. I've looked into Angular Datepicker but it's a bit confusing. Also sometimes the HTML date is of type Object and sometimes it's String so Date.parse() gives error.
Are there any developer friendly methods that does : copy HTML5 date (from datepicker) --> change to timestamp (for angular&server) --> format timestamp back to string/object (for html)? Thank You :)
Note: Angular throws a lot of annoying error in console saying dateformat is wrong (being html date type) but doesn't stop code from running
Sounds like you are doing waaay to many conversions. I would argue that there should only be one way dates are represented: as Date objects in the programming language. There are only a few conversions that need to happen:
Date <=> Integer milliseconds since the epoch to pass to server
Date <=> String human-readable format to display to user
Any thing beyond this is asking for trouble. Comparisons can be made by casting to int date.getTime(), comparing, and casting back to Date. Ditto for additions. Note that Date.parse is implementation dependent in what it will accept, although all of them will accept ISO 8601 formatted date strings anything else is guesswork. Which means you will have to deal with converting strings by hand, something like the following:
var toDate = str => {
var splitter = str.indexOf("/") === -1 ? "-" : "/";
var [mon, day, year] = str.split(splitter);
return new Date(year, mon - 1, day);
};
var toDateString = date => {
return "" + date.getFullYear() + (date.getMonth() + 1) +...
};
Note that there's no validation, that's left as an exercise to the reader.
A WORD ABOUT MOMENT.JS
moment.js is awesome. Its also huge, its a kitchen-sink API with a heft to match. You're already loading angular, so think carefully before bulking the size of your payload with another huge library.
Moment.js is a powerful date formatting and manipulation library. A lot of things you can do in Moment.js are a single line of code, which makes life a lot easier. I agree, without using a library like this date formatting and handling can be a pain.
http://momentjs.com/
EDIT: fyi, I use this with my Angular app and find it extremely useful!
Hi I am trying to figure out how to display date properly using angularjs.
My system returns the date in this fromat
c_date="\/Date(1151470800000-0500)\/"
I dont know what format is it.
I am displaying it
using <span>{{pro.c_date | date:'medium')</span>
When i run this i get date printed in same format
"/Date(1151470800000-0500)/"
Can anyone suggest how to fix this so date can be displayed properly.
Thanks
the date that you're trying to use is a invalid date or maybe I don't know what format are the system using.
The problem is that angular.js requires a data object for can format it. Not a date string.
I suppose that the date is 1151470800000 miliseconds since the epoch least 0500 for adjust hours or something.
If this is correct, you only need to make c_date a Date object before pass to view.
c_date = "\/Date(1151470800000-0500)\/";
var the_date = eval("new "+c_date.replace(/\\|\//g, ''));
http://jsbin.com/zuwizoxe/3/
Regards!
I am calling my database which contains a datetime datatype. The date looks like this:
2005-05-23 16:06:00.000
I would like to display this in a table when a user selects a certain item from a list. I call my controller action and return Json of all the times and put them in a table. The problem is the date is completely wrong. What is displayed is this:
/Date(1255470180000)/
The date that is returned isn't even parsable (which I don't want to do anyway) so I can't even get the data if I wanted to. Any ideas?
The date you're getting back is serialized to a marker and a number of milliseconds since midnight 1st Jan 1970 (in UTC). If you isolate the numeric portion, convert it into a number, and feed it into the Date constructor you'll get an actual date to work with, which you can then format as you like.
var ticks, dt;
// Isolate the numeric portion of the value
ticks = /[0-9]+/.exec(json.dateValue)[0];
// Convert to a number
ticks = parseInt(ticks);
// Convert to a date
dt = new Date(ticks);
Alternately, if the JSON serializer on the server supports a "replacer" parameter as Crockford's and ECMAScript 5th edition's do, you could supply a replacer that formatted the date into a string server-side and handle it there, since you said you don't want to parse the date client-side (although the jQuery tag suggested to me maybe you did).
The other alternative is to return the formatted string from the controller action. You could even leave the timestamp and return a second field as "Formatted Timestamp" or something similar.
var listFromDb = ...
return new Json(listFromDb.Select(itemFromDb => new List { new
{ Date = itemFromDb.Date, FormattedDate = FormatDate(itemFromDb.Date), ...}
I ended up formatting the code in the controller action instead.
I just cast the datetime property to a string using .ToString() and got the desired results.
Thanks for the help though guys.
I'm using calendar from Yahoo UI as follows:
calDate = (calDate.getMonth() + 1) +
'/' + calDate.getDate() + '/' +
calDate.getFullYear();
This displays a MMDDYYYY format.
I want to change this format to YYYY-MM-DD so that I can insert it into a MySQL database.
I changed the code to:
calDate = calDate.getFullYear() + '-'
+ (calDate.getMonth() + 1) + '-' + calDate.getDate();
It worked but the problem is now that when I want to change the selected date the calender doesn't display the date and instead shows NAN.
It's typically best to pass the date to your back end as a unix timestamp and convert it in the database itself. In the code where you construct your POST data for the server, you'd pass something like this:
var t = calDate.getTime()/1000;
Note the divide by 1000. This is required because javascript timestamps are in milliseconds, while MySQL requires seconds.
In your SQL statement, you'll pass the timestamp as is, and use the FROM_UNIXTIME function to convert it to your required format:
INSERT INTO ... VALUES ( FROM_UNIXTIME($t), ...)
Naturally there will be some code in between that converts t from javascript into $t in your back end script, and then passes that on to the SQL.
Now, if you really need to format dates on the front end, you can make use of the handy YAHOO.util.Date utility. Just do something like this:
alert(YAHOO.util.Date.format(calDate, {format: "%Y-%m-%d" }));
Much easier than calling getFullYear, getMonth, and getDate
bluesmoon has also written two excellent articles on YUIBlog on the subject of date formatting:
http://yuiblog.com/blog/2009/02/11/date-formatting-pt1-2/
http://yuiblog.com/blog/2009/02/25/date-formatting-pt2/
-Eric
You should change the format of the date just before it is inserted on the server side, let the client side have the format that it wants, and change the date around later.
cal1.cfg.setProperty("DATE_FIELD_DELIMITER", "-");
cal1.cfg.setProperty("MDY_YEAR_POSITION", 1);
cal1.cfg.setProperty("MDY_MONTH_POSITION", 2);
cal1.cfg.setProperty("MDY_DAY_POSITION", 3);