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.
Related
In javascript I have some datetime like this
Date: '2017-07-04'
I want to convert it to DateTime like ajax get result.
Expect result like this:
'/Date(1565089870830)/'
How can I make it possible?
You can use Date.parse(). This method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
var date = Date.parse('2017-07-04');
console.log(date);
The format you're trying to create is a string containing an Epoch timestamp. To create that in JS you can create a Date object from the input string and retrieve the getTime() property. Then it's just a matter of concatenating that value in to the format needed. Try this:
var date = new Date('2017-07-04');
var epoch = date.getTime();
var output = `/Date(${epoch})/`;
console.log(output);
Presumably you're working with an ASP.Net MVC site, given the date format you're trying to build. One thing to note here is that you don't need to use that format when sending DateTime values back to the server. You can send any string so long as it can be bound to a DateTime instance by the ModelBinder. As such I'd recommend using an ISO8601 format instead.
I am facing an issue while parsing JSON Date Time object using moment(of course I tried many approaches suggested in Stackoverflow but nothing worked in my case).
In my application, I'm storing a DateTime value as UTC DateTime. Now when I'm displaying I need to display it according to the browser timezone. After going through many StackOverflow questions, I used "moment.js" as below
//From server, the Date object looks like /Date(1506510057813)/
//The equivalent DateTime value stored in Database is 2017-09-27 13:00:57.813
fuction DateTimeFormatter(value)
{
if (value != undefined) {
var newValue = new Date(moment.utc(value));
//But at this line, even with just moment(value) all I am getting is DateTime which is not same as UTC time.
//I don't want any time zone to get appended all I want is just 13:00:57
var newHours = newValue.getHours() - newValue.getTimezoneOffset() / 60;
var newMinutes = (newHours + '.0').split('.')[1] * 6;
newValue.setHours(newHours);
newValue.setMinutes(newMinutes);
return moment(newValue).format(applicationTableDateFormat);
}
else
return "";
}
Please let me know what I am doing wrong or is there any other way I can display time as per browser time zone.
Once you have a UTC moment, you can convert it to local.
moment.utc(value).local().format(...)
https://momentjs.com/docs/#/manipulating/local/
But it sounds like maybe your real problem is when you store the date. If you're storing it as UTC, make sure you actually convert the local value to UTC before you store it. That way when you read it, you get a predictable value that you can safely convert to any locale.
Angularjs has its own mechanism to display formatted dates on views you just needs an absolute representation of a date and it takes care of the rest. And by absolute, I mean, a Date which is settled in a timezone whether it's utc or not, you need to know what timezone you are talking about.
The date filter
It's a filter from the core module of angularjs and it accepts:
"... either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone." (Angularjs date filter)
The problem
Angularjs need a proper date input in order to display it correctly, in your case you seem to have the milliseconds format (sort of, /Date(1506510057813)/), you could use that and extract the numeric part and input that on the pipe, or you can change the server to send the ISO 8601 date (a.k.a., yyyy-MM-ddTHH:mm:ss.sssZ).
For example:
let rawDate = '/Date(1506510057813)/';
let re = /\/Date\((\d+)\)\//g; // regex to extract number from the string date
let myDate = new Date(Number(re.exec()[1])) // extract the milliseconds
Or
let rawDate = '2017-09-27T11:00:57.813Z';
let myDate = new Date(rawDate)// and you don't need to do anything else
Either way you'd end up with something like this:
<span> {{ myDate | date }}</span>
I have a date value like this value.game_date = 2013-10-27 03:39:35 and I'm trying to parse it as follow:
moment().format(value.game_date, 'DD-MM-YYYY');
But I get this as result 29-10-2013 00:00:00 where I'm looking for this format: 29-10-10-29 without hour, what I'm doing wrong?
I think you have some typos or misinformation in your post regarding the output you're getting and what you're desiring.
Based on what appears to be a misunderstanding of moment, however, I am pretty sure that what you want is:
value.game_date = '2013-10-27 03:39:35';
var formatted_game_date = moment(value.game_date).format('DD-MM-YYYY');
// produces '27-10-2013'
moment() is a factory function which takes a date string and returns a moment instance. That moment instance then has various methods available, such as format() which takes a format string as the first param.
So your code is producing a moment instance representing current date/time (because you're not passing any params to moment()), then you ask .format() to return a string formatted using your date stamp as the formatter. Your date string doesn't have any of the things in it which format would parse and replace, so you just get back your date string.
The code I gave passes the date string to moment to produce the instance, then asks .format() for a formatted string using your desired format template.
I'm trying to create an <input type="date"/> in Emberjs and I have two problems:
In my country the date is displayed as DD-MM-YYYY format while the date field requires a MM-DD-YYYY format (and then the browser displays it according to its locale). So the date should be formatted in one way if the browser supports the date input field and in the other way if not
The date is bound to a Date object
I'm using Momentjs for formatting and Ember Data.
I'm trying to extend Ember.TextField like this:
App.DateField = Ember.TextField.extend
value: ( (key, value) ->
if value?
if /Date/.test value.constructor #I assume that if the passed value is a Date object then it is arriving directly from the model
if Modernizr.inputtypes.date
moment(value).format('YYYY-MM-DD')
else
moment(value).format('DD-MM-YYYY')
else # if the passed value is not a Date object then the user is typing into the form
if Modernizr.inputtypes.date
value = new Date('value')
else
value
).property()
type: 'date'
For browsers with date input supports this works.
For the other browsers the date is correctly displayed, but it is saved as a (wrong formatted) string in the model.
How can I maintain the correct formatting while still using Date objects in the backend?
Demo
Update
Thanks to the blog post provided in the accepted answer I was able to update the demo to do what I want (with some weirdnesses, but not relevant at this time)
Demo2
Have look at these two blog posts:
This is a simple date picker:
http://hawkins.io/2013/06/datepicker-in-ember/
This one uses the bootstrap date picker
http://hawkins.io/2013/06/fancy-ember-datepicker-with-twitter-bootstrap/
Hopefully that will help
I don't see any parsing for the string use case. You will need to use something like Date.parse to convert the string entered by the user into a Date object.
if Modernizr.inputtypes.date
value = new Date(value)
else
value = Date.parse(value)
I need to pass a date time (in 2012-09-23 21:00:00 format generated by dropdown boxes and converted to that format with javascript (client side that is)) with GET method to a php file which then gets mysql records sorted by that time.
What is the best way of passing this date?
The options I consider are:
making separate get parameters for each piece of info (e.g ?startYear=2012&startMonth=09&startDay=23&startHour=....)
this could work, but what if I add more different filters. It will be too busy there. Or it's not an issue?
Passing timestamp. I consider this to be the best option. However when I convert the date to timestamp it gives me incorrect result. The function will be below.
Passing in 2012-09-23 21:00:00 format by pre-processing with encodeURIComponent
Any suggestions?
Date to timestamp conversion (related to point 2):
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}