how to change datetime format from input using dataTables? - laravel

I followed all the tutorials from this link to create a date range filter and it worked but when I tried the results of the input it came out in an incorrect format, https://datatables.net/extensions/datetime/examples/integration/datatables.html
my data table record which was originally of type timestamps, I changed the format using carbon to Y-m-d, which I asked how to change this part of the format
minDate = new DateTime($('#min'), {
format: 'YYYY Do MMMM'
});
maxDate = new DateTime($('#max'), {
format: 'YYYY Do MMMM'
});
the table view

The problem is here:
var date = new Date( data[4] );
It should be :
var date = new Date( data[0] );

Related

How to add Date and Time to get DateTime in Laravel?

I have two columns in my DB: date and time. I want to combine them into DateTime so that I can use diff() to get a difference between the current time and the combined DateTime.
$query = DB::query("select concat(date," ",time) as datetime from TABLENAME"); using this row query you can concat the date and time DB values; and it will works like datetime value.
You can use mutators for this:
// assuming your date field is in format Y-m-d and time H:i:s
// and you want the property named someTimestamp
public function getSomeTimestampAttribute()
{
// use Carbon\Carbon for the class
return new Carbon($this->attributes['date'] . ' ' . $this->attributes['time']);
}
public function setSomeTimestampAttribute($dateTime)
{
// parse param to get string 'Y-m-d H:i:s'
$dateTime = $this->fromDateTime($dateTime);
$date = substr($dateTime, 0, 10); // Y-m-d
$time = substr($dateTime, 11); // H:i:s
$this->attributes['date'] = $date;
$this->attributes['time'] = $time;
}
Then you can do this:
// get
$model->someTimestamp; // Carbon instance depending on date & time db fields
$model->someTimestamp->diff(Carbon::now());
// set - all methods do the same
$model->someTimestamp = new Carbon('2014-08-31 11:55:00');
$model->someTimestamp = new DateTime('2014-08-31 11:55:00');
$model->someTimestamp = '2014-08-31 11:55:00';
// then this is true
$model->date; // 2014-08-31
$model->time; // 11:55:00
// so you can now call ->save() on the model and values in db will be correct
Concatenating the two variables storing wasn't enough, it needed more. I am using Laravel, so in my case this did the trick:
$datetime = $date.' '.$time;
$datetime = new DateTime($datetime);
All I needed was a DateTime object, and this is how I got it. So after this I can easily get the difference between two DateTime objects.
$currentDateTime = new DateTime(); //Returns current time & date in a DateTime object
$difference = $currentDateTime->diff($datetime);
$difference has all that I wanted.

linq query issues with date type data

I want to retrieve the data based on sku number like in below code,in this process i got all data same as it is in database but "date type" value is display like "01/01/0001".But i need to "date type" data like as it is in database date.any modifications i need to do .please help me out.
public IEnumerable<SKUDvo> getdatabysku()
{
eshop_dbContext dbcontext123 = new eshop_dbContext();
var productinfoQuery321 = (from productInfo321 in dbcontext123.ProductMasters
where productInfo321.SKU == "s121"
select productInfo321);
IList<SKUDvo> productList123 = new List<SKUDvo>();
foreach (var proitems in productinfoQuery321)
{
productList123.Add(new SKUDvo
{
skuno = name,
ProductId = proitems.ProductId,
CategoryID = proitems.CategoryID,
ManufaturerId = proitems.ManufaturerId,
ItemNo = proitems.ItemNo,
ProductName = proitems.ProductName,
DeletedInd = proitems.DeletedInd,
});
}
return productList123;
}
My table is like below.
empid ename dateofjoin
10 sarath 26/02/2003
20 jai 16/03/2001
my result is like below
10 sarath 01/01/0001
20 jai 01/01/0001
It looks like you have an DateTime that hasn't been set. The default value of a DateTime is "01/01/0001 00:00:00".
// outputs the value of an empty DateTime: "01/01/0001 00:00:00"
Console.WriteLine(default(DateTime));
Are you sure that the dateofjoin is assigned? I don't see it in you code.

How to format DateTime from DB to be displayed throughout the site, using ASP.Net MVC 3 Razor C#?

I've been looking for an answer since yesterday with no avail. I've tried things like Model binders, layout templates (doesn't apply on my case), etc.
Let me clarify what I actually need.
I have many DateTime fields on many tables in a SQL Server 2008 R2 database. They're stored on the London Timezone.
I've managed (with help from you guys) to convert the DateTime to the user's Timezone and display them correctly.
What I need now is a way to automate this. Everytime the site displays DateTime coming from the database, it needs to be converted beforehand.
The input will stay as it is.
If it was on WebForms development - that I'm used to - I'd just create a handler. But I don't know what's the best practice on MVC 3 Razor.
Does anyone can give me some directions here, please?
Thanks in advance.
Complementing
That's the code that converts the DateTime:
// Timezone data provider
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
// Database Timezone = London
var londonTimeZone = timeZoneProvider["Europe/London"];
//// Getting date/time from the database and mapping it as being local to London timezone
//var yourDateFromDb = new DateTime(source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second, source.Millisecond);
//ZoneLocalMapping map = londonTimeZone.MapLocal(LocalDateTime.FromDateTime(yourDateFromDb));
//// This is the date/time with the correct offset (taking into account DST etc)
//var zonedDbDateTime = map.First();
// Jon Skeet suggestion instead of using the Mapping
// http://stackoverflow.com/questions/16164994/datetime-conversions-using-nodatime-on-asp-net-mvc-3-razor-website-how-to/16178730?noredirect=1#16178730
//
var dateTimeFromDb = new DateTime(source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second, source.Millisecond);
var zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(dateTimeFromDb));
// Map the London zoned date/time to the users local date/time (saved on the Session)
var usersTimezoneId = (HttpContext.Current.Session["timezoneid"] != null ? HttpContext.Current.Session["timezoneid"].ToString() : "UTC");
var usersTimezone = timeZoneProvider[usersTimezoneId];
var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);
return usersZonedDateTime.ToDateTimeUnspecified();
I've found a solution going for a DateTime extension:
public static DateTime ToLocalTimeZone(this DateTime dateTime) {
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
var londonTimeZone = timeZoneProvider["Europe/London"];
var dateTimeFromDb = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day,
dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
var zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(dateTimeFromDb));
var usersTimezoneId = (HttpContext.Current.Session["timezoneid"] != null ? HttpContext.Current.Session["timezoneid"].ToString() : "UTC"); var usersTimezone = timeZoneProvider[usersTimezoneId]; var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);
return usersZonedDateTime.ToDateTimeUnspecified();
}
Not sure about best practices, because as I've pointed out, I'm totally new to the MVC model. But it's doing the trick.

How do I display only datepart of datetime field in LINQ query?

I have a datetime field in a database which when retrieved should only display the date without the time. Can you please let me know how to do it? Here is the query I wrote:
var queryProductEventCustomers = (from r in DbContext.ProductEventCustomers
from s in DbContext.CustomerProducts
where r.Customers_Id == customerID && r.Customers_Id
== s.Customers_Id && s.Products_Id == productID
select new
{
r.Id,
r.Customers_Id,
r.StartTime
The starttime is a datetime field. So, can you please let me know how to do it?
Use the Short Date format:
r.StartTime.ToString("d", DateTimeFormatInfo.InvariantInfo)
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
The link shows you how to work with all standard date and time formats.
Use the ToShortDateString() method on DateTime.
select new
{
Id = r.Id,
Customers_Id = r.Customers_Id,
Date = r.StartTime.ToShortDateString()
}
Just choose the date portion:
select new
{
Id = r.Id,
Cust_id = r.Customers_Id,
Date = r.StartTime.Date
}
Try this
select new
{
ID = r.Id,
CustomerID = r.Customers_Id,
StartDate = r.StartTime.ToString("dd/MM/yyyy")
}

C# linq dates between

I am tring to get a list of dates from my db that will eventually be used to populate a calendar. Each 'calendar event' has a start date & end date, i need to get all dates between & including the start & end date.
i am stuck on the WHERE statement, as i am not sure what to use for this
public List<EventFeed> GetCalendarDates()
{
return (from eventsList in GetEventsList()
select new EventFeed()
{
//EventDate = todo
}).ToList();
}
UPDATE
just to be clear, if i have a calendar event called foobar which starts on 22/08/2010 and ends on 24/08/2010, then i want my list return:
22/08/2010,
23/08/2010,
24/08/2010
thanks
kb
I had to do something similar recently, I used a Func<> to extract the dates from the range and used the result in the linq query.
I have added the same Func to your Linq query below. You didn't specify the name of the object that is returned by GetEventsList() so just replace the EventItem type for the first type parameter in the Func<> with whatever type you need.
public static List<EventFeed> GetCalendarDates()
{
Func<EventItem, List<DateTime>> extractEventDates = eventItem =>
{
var dates = new List<DateTime>();
for (var date = eventItem.StartDate;
date <= eventItem.EndDate;
date = date.AddDays(1))
{
dates.Add(date);
}
return dates;
};
return (from eventItem in GetEventsList()
from eventDate in extractEventDates(eventItem)
select new EventFeed
{
EventDate = eventDate
}).ToList();
}
You mean you want to select all the events that started on or after start date and ended on or before end date!
If yes, then this will help
var query = from #event in events
where #event.Start.Date >= startDate.Date
&& #event.End.Date <= endDate.Date
select #event;

Resources