Newbie question about using the DateTime method to set a schedule inside a Telerik calendar. I want to use the Telerik controls calendar to set a schedule for a music bands tour schedule.
I can't seem to get the desired results. Below is the code in my SampleAppointmentSource CS file. I thought that by setting the DateTime.Parse("5/19/2013") that then in all of the appointments when I use the AddDays(1) or AddDays(20) the appointemnts would follow the DateTime.Parse("5/19/2013") pattern but it doesn't. The appointments always use the current date and time (Now). When I add the days, the appointments aren't added to the Parsed date ("5/19/2013"), they are added to the current DateTime. Like the appointments are always referenced to the current system date.
I hope that wasn't to confusing....
What do I need to use to get the desired results?
Is it because of the DateTime.Now.AddDays(1) line? Should it not be DateTime.Now?
{
public class SampleAppointmentSource : AppointmentSource
{
public SampleAppointmentSource()
{
DateTime date = new DateTime();
date = DateTime.Parse("5/19/2013");
}
public override void FetchData(DateTime startDate, DateTime endDate)
{
this.AllAppointments.Clear();
this.AllAppointments.Add(new SampleAppointment()
{
StartDate = DateTime.Now.AddDays(1),
EndDate = DateTime.Now.AddDays(1),
Subject = "Jackson W/Warren Hayes",
AdditionalInfo = "Fain Feild",
Location = "LoserVille,Kentucky",
});
Fleshing out my comment to your question. You create a DateTime object called date and never use it. DateTime.Now will always return an object containing the current DateTime. You need give your date DateTime object module Level scope so you can access it in your FetchData method. See if something like this works for your.
public class SampleAppointmentSource : AppointmentSource
{
DateTime date;
public SampleAppointmentSource()
{
date = DateTime.Parse("5/19/2013");
}
public override void FetchData(DateTime startDate, DateTime endDate)
{
this.AllAppointments.Clear();
this.AllAppointments.Add(new SampleAppointment()
{
StartDate = date.AddDays(1),
EndDate = date.AddDays(1),
Subject = "Jackson W/Warren Hayes",
AdditionalInfo = "Fain Feild",
Location = "LoserVille,Kentucky",
});
}
}
Related
I am trying to get DataTime from database in Persian Date Fromat,
For this task i made an extinsion method,
and my App Culture is FA-fa, So the DateTime.Now returning Persian Date.
Here is cultureInfo
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fa-AF");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fa-AF");
Here is My Code in ViewModel Which makes error:
long mntRevenue = (long)db.StudentFees
.Where(f => DateConverter.ToPersianDate(f.Date).Month == DateTime.Now.Month).Sum(s => s.Pay);
Error is:
System.InvalidOperationException: 'The LINQ expression 'DbSet()
.Where(s => (DateTime?)s.Date
.ToPersianDate().Month == DateTime.Now.Month)' could not be translated. Additional information: Translation of method 'SchoolViewModel.ViewModels.DateConverter.ToPersianDate' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information.
Translation of method 'SchoolViewModel.ViewModels.DateConverter.ToPersianDate' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
My Extinsion Method is:
public static class DateConverter
{
#region Static Methods
public static DateTime ToPersianDate(this DateTime? dt)
{
try
{
DateTime dateTime = dt ?? DateTime.Now;
PersianCalendar persianCalendar = new PersianCalendar();
string year = persianCalendar.GetYear(dateTime).ToString();
string month = persianCalendar.GetMonth(dateTime).ToString()
.PadLeft(2, '0');
string day = persianCalendar.GetDayOfMonth(dateTime).ToString()
.PadLeft(2, '0');
string hour = dateTime.Hour.ToString().PadLeft(2, '0');
string minute = dateTime.Minute.ToString().PadLeft(2, '0');
string second = dateTime.Second.ToString().PadLeft(2, '0');
return DateTime.Parse(String.Format("{0}/{1}/{2} {3}:{4}:{5}", year, month, day, hour, minute, second));
}
catch { return DateTime.Now; }
}
#endregion
}
I want to get date from database and compare it with Current Month and give the compare result to linq expression. The DateTime should be in the Persian Format (Shamsi Date).
Thanks for all who leaves comments, Specially #lets do it.
I found the solution,
I just Remove the ToPersianDate Extinsion Method and Add DateAndPay class,
DateAndPay Class:
public class DateAndPay
{
public DateTime Date { get; set; }
public int Pay { get; set; }
}
Here it is:
PersianCalendar persianCalendar = new PersianCalendar();
int month = persianCalendar.GetMonth(DateTime.Now);
using AppDbContext db = new();
List<DateAndPay> studentFee = await db.StudentFees.Select(f => new DateAndPay { Date= f.Date,Pay= f.Pay }).ToListAsync();
long mntRevenue = (long)studentFee.Where(f => persianCalendar.GetMonth(f.Date) == month).Sum(f=> f.Pay);
I want to store a DateTime instance into MongoDB using C#. As mongodb uses ISO 8601 as format, the date which I am passing is getting stored with a timestamp which is making querying using that date field a nightmare. I tried DateTime.Now, DateTime.UtcNow, BsonDateTime object but all are saving with current timestamp only. Is there a way using which I can make my date field to store date and rest as Zeros,
Thanks
Piyush Kumar
You can set up a class map for your class to only store the date part of the datetime with the following code:
BsonClassMap.RegisterClassMap<Order>(map =>
{
map.MapProperty(x => x.Date)
.SetSerializer(DateTimeSerializer.DateOnlyInstance);
});
then when execute the following
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Order>("orders");
await collection.InsertOneAsync(new Order
{
Name = "MyOrder", Date = DateTime.UtcNow.Date
});
we'll get the following in the database
> db.orders.find().pretty()
{
"_id" : ObjectId("5ed8fb7050eb018e5ee13e73"),
"Date" : ISODate("2020-06-04T00:00:00Z")
}
I have a web api set up where I'm displaying information on my site via entity framework. I'm filtering my data so it only pulls back the specific parts I want, which includes a DateTime value.
[HttpGet]
public IEnumerable<Log> XmlLog()
{
var userLog = _db.Logs.Where(x => x.EngineType == "Xml");
return userLog .ToList();
}
This displays my date as:
2019-02-05T15:11:50.39
What I need to do is change the DateTime format to be something else. Ideally:
Saturday 2 February 9:12:30
On my linq call I've tried the following:
[HttpGet]
public IEnumerable<Log> XmlLog()
{
var userLog = _db.Logs.Select(d => d.LogDate.ToString("f")).Where(x => x.EngineType == "Xml");
return userLog .ToList();
}
And on my model itself I have tried the following attributes:
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm:ss}")]
public DateTime LogDate { get; set; }
Neither of my attempts has worked. What is it I'm doing wrong in my statements?
The above is written in DotNet 4.7 and not in DotNetCore.
As John has commented, your LINQ should be throwing an exception, because you first select strings, and then try to filter them as though they are objects.
But this approach is backwards anyway. This is just about getting the data, so it should just stay as it is, without any formatting. Let your view layer be responsible for formatting.
The DisplayFormat attribute is great, but only if you are using Html.DisplayFor/Html.EditorFor helpers. If you are doing just something like #Model.LogDate in your view, consider calling ToString(format) with the format you need.
Finally, your format does not look like example you wish it was. The correct format you are looking for is: dddd, dd MMMM HH:mm:ss.
All in all, leave the filter as it is, and either use DisplayFor with this annotation:
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dddd, dd MMMM HH:mm:ss}")]
public DateTime LogDate { get; set; }
...
#Html.DisplayFor(m => m[i].LogDate)
Or don't bother with any annotations, and just use
#Model[i].LogDate.ToString("dddd, dd MMMM HH:mm:ss")
In our ASP.NET MVC 5 application we have user profiles with a Timezone ID (IANA).
public class User
{
public int Id { get; set; }
public string TimeZoneId { get; set; }
}
The task is to send all users an email at 6 AM local time. Our plan is to send out emails every hour to all timezones where the local time is 6 AM at that point in time (calculated based on the UTC time of the server).
Since we only have the Timezone ID to go by, I was hoping to get the corresponding Timezone IDs for, let's say, offset -4:00:00 -- taking into account DST.
string[] timezoneIds;
I could then query my database like so:
db.Users.Where(x => timezoneIds.Contains(x.TimeZoneId));
My question is, obviously, is this a decent idea or are there best practices for this problem that I am not aware of?
Thanks.
Simpler code for the "building a dictionary" that Serge shows: use LINQ's lookup, DateTimeZone.GetUtcOffset, and Offset keys instead of TimeSpan values:
var now = SystemClock.Instance.GetCurrentInstant();
var provider = DateTimeZoneProviders.Tzdb;
var idsByCurrentOffset = provider.Ids.ToLookup(id => provider[id].GetUtcOffset(now));
Then you can use:
var offset = Offset.FromHours(5);
foreach (var id in idsByCurrentOffset[offset])
{
...
}
(You don't even need to check for existence first, as the lookup indexer returns an empty sequence when presented with a key that doesn't exist in the lookup.)
You could try the following:
First create a dictionary with all the offsets and the timezones belonging to that offset
Instant now = SystemClock.Instance.Now;
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
Dictionary<TimeSpan, List<string>> timezonesForOffset = new Dictionary<TimeSpan, List<string>>();
foreach(var id in timeZoneProvider.Ids){
ZonedDateTime zdt = now.InZone(timeZoneProvider[id]);
var timespan = zdt.Offset.ToTimeSpan();
if(timezonesForOffset.ContainsKey(timespan)){
timezonesForOffset[timespan].Add(id);
} else {
timezonesForOffset[timespan] = new List<string> {id, };
}
}
After you have done that you could use the following snippet to get all users within a certain timezone
var timespan2 = new TimeSpan(1,0,0);
var timezonesWithOffset = timezonesForOffset[timespan2];
var usersinTimezone = db.Users.Where(x=> timezonesWithOffset.Contains(x.TimezoneId)).ToList();
That would get all users in the timezone utc+1
I am using daterangepicker. In my form, I have two hidden fields:
#Html.HiddenFor(x=> x.Header.StartDate, new {id="startdate"})
#Html.HiddenFor(x => x.Header.EndDate, new { id = "enddate" })
I also have the input which is for the dates to be selected from:
<input class="input-sm form-control" placeholder="Enter your dates" type="text" name="daterange" value="" />
When the user has selected an end date, the two hidden fields are populated with the start and end date, respectively.
The daterangepicker is managed via JS:
$(function () {
$('input[name="daterange"]').daterangepicker({
locale: {
format: 'DD/MM/YYYY'
},
"autoApply": true
});
$('input[name="daterange"]').val('');
$('input[name="daterange"]').on('apply.daterangepicker', function (ev, picker) {
var startdate = picker.startDate.format('DD/MM/YYYY');
var enddate = picker.endDate.format('DD/MM/YYYY');
$("#startdate").val(startdate);
$("#enddate").val(enddate);
});
});
My HeaderViewModel looks like this (setting the format makes no difference):
public class HeaderViewModel
{
//[DataType(DataType.Date), DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
// [DataType(DataType.Date), DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
}
If I choose a date with a day less than 12, eg: 11 March 2015, it works. However, if I select a date, say, 23 March 2015, it will not work because the date is invalid... it is expecting a US format.
I am using SQL server 2012 and have set the language to British English.
Anyone have any ideas? It's killing me.