I am using MySQL which stores dates in the format 'yyyy-mm-dd'.
I have a layout where one section shows a grid. The records in this grid display the date the record was first created. I need the date to be in the format of 'mm/dd/yyyy'.
This is how the date field in the grid is setup:
{ field: 'incident_date', caption: 'Incident Date', size: '150px', searchable: true, type: 'date', format: 'mm/dd/yyyy' },
I also have a form that opens for the user to edit the record. This is the date field code on that form:
{ name: 'incident_date', type: 'date', format: 'mm/dd/yyyy', required: true },
In w2ui-1.4.2.min.js I have these settings:
"date_format" : "mm/dd/yyyy",
"date_display" : "mm/dd/yyyy",
On the form the date field has a popup calendar that appears when this field is selected. When you select a date in the calendar the field gets filled in with the date you selected, in the format of "mm/dd/yyyy".
Now that you have an idea of how things are setup, when you save the record, any date you enter shows up in the grid as '0000-00-00'. if you use phpMyAdmin to look at the actual data in the table the date stored is '0000-00-00'
What I want is for the date to be displayed in the grid and in the form in the format of 'mm/dd/yyyy'. How can I accomplish this?
Thanks,
TD
For anyone who may have the same problem, the easiest way to fix this problem is to return your date from the server in mm-dd-yyyy format. For instance, if using MySQL you can use the following function in your SQL SELECT statment, date_format(yourDate, '%m-%d-%Y').
The other fix is to modify w2ui.js. In my opinion the date formatting in w2ui ver. 1.5 does not work correctly. The problem is with w2utils.formatters for dates. It uses the same date format for checking to see if it is a valid date as it does to format the date. So if yyyy-mm-dd is passed into params, it uses that to see if it is a valid date and fails. I have made some changes that worked for me and are listed below.
// MODIFIED LOCALE TO USE yyyy-mm-dd DATE FORMAT
var w2utils = (function ($) {
var tmp = {}; // for some temp variables
var obj = {
version : '1.5.RC1',
settings : {
"locale" : "en-us",
//"dateFormat" : "m/d/yyyy",
"dateFormat" : "yyyy-mm-dd",
"timeFormat" : "hh:mi pm",
"datetimeFormat" : "m/d/yyyy|hh:mi pm",
//"datetimeFormat" : "yyyy-mm-dd|hh:mi pm",
// MODIFIED DATE FORMATTER. ALWAYS RETRIEVE DEFAULT DATEFORMAT AND USE WHEN CHECKING FOR VALID DATE.
w2utils.formatters = {
'date': function (value, params) {
if (params === '') params = w2utils.settings.dateFormat; // DELETED
var defaultFormat = w2utils.settings.dateFormat; //ADDED
if (value == null || value === 0 || value === '') return '';
//var dt = w2utils.isDateTime(value, params, true);
//if (dt === false) dt = w2utils.isDate(value, params, true);
var dt = w2utils.isDateTime(value, defaultFormat, true); // CHANGED
if (dt === false) dt = w2utils.isDate(value, defaultFormat, true); // CHANGED
return '<span title="'+ dt +'">' + w2utils.formatDate(dt, params) + '</span>';
},
Hope this helps someone. I am working on getting these changes added to repository.
Thanks
John
Related
I am able to fetch the date from the API but unable to fetch the time and I want to display date and time beside the message. If i receive any message then it should show "today 02:21 pm" else for earlier messages it should display "11-09-2019 06:01 am".
Json data that i received through the api:
[
{
"id": "14526fgy",
"message" : "Hello",
"messageime" : "2019-11-12T03:07:58.359"
},
{
"id": "14546fgy",
"message" : "Hi",
"messagetime" : "2019-12-12T10:07:58.359Z"
}
]
I've attached an example inorder to display date and time. can anyone help me with this?
First you need to split the date from the API by the T ,
let dateSplit = result[0].messagedateTime.split("T");
Now you have an array with 2 elements ['2019-11-12','03:07:58.359']
SO first you need to create a variable (e.g todayDate) that contains todays date in the format of the above ie YYYY-MM-DD . You can get from the internet how to extract todays date into that format or create your own custom function to convert date in that format.
After that you need to compare
let firstPart = (todayDate === dateSplit[0])?'today':dateSplit[0];
So second part contains time, you can always refer the moment library to change the date and time formats according to how you need. So that wont be a problem. Hence your main logic is implemented in the above steps i mentioned.
let finalString = `${firstPart} , ${secondPart}`
this final string will be displayed under the chats. And here the second part variable is nothing but the time whihc is extracted according to your format by the moment.js after you pass the dateSplit1 whihc contains the time, Hope you are clear, otherwise ask me for doubts.
Update answer :
displayDate(messagedateTime) {
let time = messagedateTime;
let arr = time.split("T");
let date = new Date().getDate()
let month = new Date().getMonth() +1
let year = new Date().getFullYear()
let todayDate = `${year}-${month}-${date}`
let firstPart = (todayDate === arr[0])?'today':arr[0];
let secondPart = (arr[1].split("."))[0]
let finalString = `${firstPart} ${secondPart}`
return finalString
console.log(finalString,'wowow')
}
You can also try the js fiddle link Check here to play around
Just to show you how to use it. make it string to make it in your own format then if moment library or any other library don't have that custom format you want.
let datetime = "2019-11-13T03:07:58.359";
var d = datetime.split("T");
console.log(d);
let timeday = moment(d[0]).calendar();
timeday=timeday.toString();
timeday=timeday.replace(" at","");
console.log(timeday.toString());
I have to define a date in my Student Object,like that:
var Students = new List<Student>
{
new Student{ FirstName="Student ",dateBirth=DateTime.Today }
};
Students.ForEach(s =>
{
s.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
context.Students.Add(s);
context.SaveChanges();
});
but I get this format when I run my project:
[{ FirstName: "Student ", dateBirth: "/Date(1457132400000)/" }]
the problem is that the date format is added exactly to the DataBase Student Table (like yyyy-MM-dd hh:mm:ss). I work with xampp MySQL
any idea please how can I solve this problem,and display the date correctly?
Try formatting the date time like this:
new Student{FirstName="Student ",dateBirth=DateTime.ToString("MMMM dd, yyyy")}
You can read up on the details here.
Custom Date and Time Strings
I''m using EF to query the database using anonymous type.
here the code I use for EF
public JsonResult OverdueEventsCustom()
{
var eventCustomOverdue = _eventCustomRepository.FindOverdueEventsCustom();
return Json(eventCustomOverdue, JsonRequestBehavior.AllowGet);
}
public IQueryable<dynamic> FindOverdueEventsCustom()
{
DateTime dateTimeNow = DateTime.UtcNow;
DateTime dateTomorrow = dateTimeNow.Date.AddDays(1);
return db.EventCustoms.Where(x => x.DateTimeStart < dateTomorrow)
.Select(y => new { y.EventId, y.EventTitle, y.DateTimeStart});
}
Inspecting using the debugger I see the properties is in this format
Date = {16/08/2012 00:00:00}
The resultfor the JSON is
[{
"EventId": 1,
"EventTitle": "Homework Math",
"DateTimeStart": "\/Date(1345108269310)\/"
}, {
"EventId": 4,
"EventTitle": "Homework help with Annie",
"DateTimeStart": "\/Date(1345108269310)\/"
}, {
"EventId": 6,
"EventTitle": "Physic laboratory",
"DateTimeStart": "\/Date(1345108269310)\/"
}]
I need the the json in this format
"DateTimeStart": "(16/08/2012)"
Any idea what i'm doing wrong here? thanks for your help
Related articles
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
How do I format a Microsoft JSON date?
"\/Date(1345108269310)\/" is the correct way to pass a Date to javascript. The way I see it, you have two options here:
If you do not explicitly need the value as a date, you could just pass a string to the JSON variable, containing the pretty-printed date.
Something along the lines of:
DateTimeStart: String.Format("{0: dd-MM-yyyy}", myDate)
If you will still need to use the variable a a date in javascript (for calculations for example), the most consice and readably way would be to create a javascript function that converts said date into the pretty-printed string you want (I don't know if such a function already exists. It isn't too hard to create though:
function prettyDate(date) {
return date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear();
}
I would suggest passing it along as a string from you code behind, as it is more readable. But that only works if you do not need to use the date except for displaying.
I use jqGrid and my grid definition is like that:
...
colNames:['Type','Date','Message','User Name','Host'],
colModel:[{name:'type',index:'type', width:100},
{name:'date',index:'date', sorttype:'date', formatter:'date',
formatoptions: {newformat:'d-M-Y'}, width:100},
{name:'log',index:'log', width:200},
{name:'username',index:'username', width:50},
{name:'host',index:'host', width:50}],
...
When I debug my coming data one of the date value (it is Number) is as follows:
1322550786997
Grid shows it like that:
29-Nov-2011
Everything is OK till this point. However when I want to sort my date column it doesn't change anything.
Any ideas?
The problem is that decoding of the Unix (formatoptions: {srcformat: 'U', newformat: 'd-M-Y'}) date 1322550786997 get us 19-Dec-43879 and not 29-Nov-2011. You correct representation of the date will be the string "\/Date(1322550786997)\/" instead of the number 1322550786997.
See the demo:
UPDATED: You can also use the following custom formatter as a workaround
formatter: function (cellval, opts) {
var date = new Date(cellval);
opts = $.extend({}, $.jgrid.formatter.date, opts);
return $.fmatter.util.DateFormat("", date, 'd-M-Y', opts);
}
It creates Date and then use original date formatter to convert it to the format 'd-M-Y'. See here the demo.
I want to split a returning text to become an individual string but i am noobie in extjs.Pls help me if any idea with it...thankz
my example code:
//my return "record" string is "1: 3-4-2011 to 9-4-2011"
Ext.getCmp('cboWeek').on('select', function(box, record, index)
{
DateFrom = new Date(record).format('m/d/Y');//split to 3-4-2011
DateTo = new Date(record).format('m/d/Y'); //split to 9-4-2011
Store.load({ params: {dateFrom : DateFrom, dateTo: DateTo }});
});
i think what you want is:
// if record is "1: 3-4-2011 to 9-4-2011"
var matches = record.match(/[0-9]+-[0-9]+-[0-9]+/g);
// matches[0] will be 3-4-2011 and matches[1] will be 9-4-2011
Store.load({ params: {dateFrom : matches[0], dateTo: matches[1] }});
</pre>
just a note: your dates are not what can be parsed using Date object neither using Ext.Date.parse, because month / day must be 2digits, if you manage to get 3-4-2011 to something like 03-04-2011 by doing "3-4-2011".replace(/([0-9]{1})[^0-9]+/g, '0$1-') you can get Date object using parse method of ext's date: Ext.Date.parse('03-04-2011', 'd-m-Y') then you can use format method on Date object