How to convert Datetime.utcnow to DateTime,UTCtoLocal()? - c#

when convert utcnow to local time, it shows error like
"LINQ to Entities does not recognize the method 'System.DateTime
ToLocalTime()' method, and this method cannot be translated into a
store expression."
I am using SQL Server 2014 and not mango db. It will work when I use the function UTCtoLocal outside the query. But I need to use it within the linq query to speed up the execution. There is any other way to do that.
group new
{
Id = ord.Id,
ShipmentInfoId = shipment.Id,
PartnerName = partner.Name,
PartNumber = ordItem.SellerProductID,
OrderNumber = ord.UniqueOrderID,
PartCount = shipment.PartCount,
DeliveryDate = ord.DeliveryDate,
IsSentInvoice = shipment.IsSentInvoice != null ? shipment.IsSentInvoice : false,
IsSentASN = shipment.IsSentASN != null ? shipment.IsSentASN : false,
ShippingPartCount = 0,
IsManualEntered = ord.IsManualEntered,
LastGeneratedInvoiceDate = shipment.LastGeneratedInvoiceDate.Value.UtcToLocal(),
LastGeneratedASNDate = shipment.LastGeneratedASNDate.Value.UtcToLocal(),

Solution here by playing around with your DateTimeKind.Utc and ToLocalTime()
var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
Console.WriteLine(s);
Source: datetime to string with time zone

Related

convert datetime passed into parameter to a string c#

I would like to convert a datetime passed into parameter into a string using this function but it doesn't work. Could anyone help me ? Thank you in advance
Here is my function
public string ConvertDateTimeToString(DateTime date)
{
string date_str = date.ToString("dd/MM/yyyy HH:mm:ss");
return date_str;
}
and after when i create a new dateTime object
DateTime dateTest = new DateTime(2008, 5, 1, 8, 30, 52);
ConvertDateTimeToString(dateTest);
Console.WriteLine(dateTest); /// show this {01/05/2008 08:30:52}
The "ConvertDateTimeToString" will create a new string.
The existing DateTime still untouched.
You have to use the new string in your Console.WriteLine :
var dateString = ConvertDateTimeToString(dateTest);
Console.WriteLine(dateString);

Converting 1000s ExpandoOject / dynamic to static type takes forever

I am trying to convert a list of 1000s dynamic (that I get from CsvHelper reading csv file) into static type but its taking forever.
Here's code:
dynamic object
MyObj {
id =1, prop1=1,prop2=2,prop3=3...
}
result
PObj1 { oid = 1 , name = "Property 1", value = "1" }
PObj2 { oid = 1 , name = "Property 2", value = "2" }
PObj3 { oid = 1 , name = "Property 3", value = "3" }
Code to convert
var imp = rows.SelectMany(x => map.Keys.ToList().Select(k => new PObj
{
OID = (((IDictionary<string, object>)x)["oid"] ?? "").ToString(),
Name = k,
Value = ToDate((((IDictionary<string, object>)x)[map[k]] ?? "").ToString())
}).ToList()).ToList();
map contains list of properties about 40-50
map<string,string>{
{"Property 1","prop1"},
{"Property 1","prop2"},
{"Property 1","prop3"}
...
}
ToDate function
private DateTime? ToDate(string strDate)
{
strDate = strDate.Split(' ')[0];
strDate = strDate.Replace('-', '/').Replace('.', '/');
DateTime? dt = null;
try
{
dt = DateTime.ParseExact(strDate, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
} catch { }
return dt;
}
map can contain any number of peroperties hence expandoObject will have dynamic number of properties.
Is there any way I can improve the performance?
The reason I need to do this conversion is because I need to than send this as table to a stored procedure therefore converting expandoObject straight into table creates issue if number properties in object changes as this mean number of column will also change in table.
I am open to other solutions as well if works in above situation.
seems like it was my pc (running windows on mac). Same code now works fine
rows.ToList().ForEach(x => imps.AddRange(map.Keys.Select(k => new ImportMilestone
{
JVSiteID = (((IDictionary<string, object>)x)[siteid] ?? "").ToString(),
Milestone = k,
MilestoneValue = ToDate((((IDictionary<string, object>)x)[map[k]] ?? "").ToString())
}).ToList()));

C# - Format event log query with multiple arguments

I have the following event log query where I need to filter by event ID and specific date range for the Time Created. Here is what I current have:
var _PRINTINGDOCUMENTEVENTID = "307";
var startTime = System.DateTime.Now.AddMinutes(-10);
var endTime = System.DateTime.Now
var query = string.Format("*[[System/EventID={0}] and [System[TimeCreated[#SystemTime >= {1}]]] and [System[TimeCreated[#SystemTime <= {2}]]]", _PRINTINGDOCUMENTEVENTID, startTime.ToUniversalTime().ToString("o"), endTime.ToUniversalTime().ToString("o"));)
var logQuery = new EventLogQuery("Microsoft-Windows-PrintService/Operational", PathType.LogName, query );
var reader = new EventLogReader(logQuery);
I get the following error when I try to debug the event log query:
The specified query is invalid
Here is what the query value looks like while debugging:
"*[[System/EventID=307] and [System[TimeCreated[#SystemTime >=
2016-03-28T22:51:23.9082575Z]]] and [System[TimeCreated[#SystemTime <=
2016-03-28T23:01:23.9092576Z]]]"
How do I fix this issue?
I was able to determine the correct format for filtering by event id and a date range for TimeCreated
var eventId = "307";
var startTime = System.DateTime.Now.AddMinutes(-10);
var endTime = System.DateTime.Now;
var query = string.Format(#"*[System/EventID={0}] and *[System[TimeCreated[#SystemTime >= '{1}']]] and *[System[TimeCreated[#SystemTime <= '{2}']]]",
eventId,
startTime.ToUniversalTime().ToString("o"),
endTime.ToUniversalTime().ToString("o"));
Have you tried surrounding your formatted DateTimes with ticks?
and [System[TimeCreated[#SystemTime >= '{1}']]]

How to format DateTime comparison value in AX Query Service

I am working with the Dynamics AX 2012 R2 query service and need to filter (set a range) on the modifiedDateTime field of the CustTable. I am creating a QueryDataRangeMetadata object and setting its properties. I can filter properly on integer values but not DateTimes.
I was able to figure out that the comparison operator is actually embedded with the value. I have tested this with integer fields and it does work for but I have not been able to figure out how to format a DateTime value so that it is properly evaluated. The code below doesn't work. The range is simply ignored and all records from the CustTable are returned.
public static void RangeTest()
{
var client = new QueryServiceClient();
var dataSource = new QueryDataSourceMetadata
{
Table = "CustTable",
Name = "CustTable",
HasRelations = false,
Enabled = true,
DynamicFieldList = true // get all fields
};
var range = new QueryDataRangeMetadata
{
TableName = "CustTable",
FieldName = "modifiedDateTime",
Value = ">2013-02-05T21:17:33Z", // <-- ISSUE: notice the operator with the value!
Enabled = true
};
dataSource.Ranges = new QueryRangeMetadata[] { range };
var sort = new QueryDataOrderByMetadata
{
DataSource = "CustTable",
FieldName = "modifiedDateTime",
SortOrder = SortOrder.Ascending
};
var query = new QueryMetadata
{
QueryType = QueryType.Join,
DataSources = new[] { dataSource },
OrderByFields = new QueryOrderByMetadata[] { sort }
};
Paging paging = null;
var dataSet = client.ExecuteQuery(query, ref paging);
Console.WriteLine(dataSet.Tables[0].Rows.Count);
}
I have also tried these formatting variations with no success:
Value = ">2013-02-05 21:17:33"
Value = ">2013-02-05T9:17:33"
Value = ">'2013-02-05T9:17:33'"
Value = ">2013-02-05T21:17:33Z"
Anyone know what the format of the DateTime is supposed to be in this case?
After iterating over a bunch of DateTime formatting variations I just copied and pasted a value from the UI and guess what? It worked. This is the snippet:
var range = new QueryDataRangeMetadata
{
TableName = "CustTable",
FieldName = "modifiedDateTime",
Value = ">2/5/2013 9:17:33 PM",
Enabled = true
};
So the format seems to be: comparison_operatorMM/DD/YYYY hh:mm:ss AM
I am in the US and the format is month-first. I imagine that other locales would have to format differently, e.g. day-first.

DateTime class common error displayed again

I run into a little common problem with datetime class that I have no idea how to resolve.
I don't know what the error is but I see the troubleshooting tips are displayed as
When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object. Make sure your method arguments are in the right format.
Here is the piece of code I extract from my program,
public IEnumerable<CONTACT_INFO> GetContactInfo(string tableName)
{
DataTable dt = GetUserInfo(tableName);
List<CONTACT_INFO> lst = new List<CONTACT_INFO>();
foreach (DataRow row in dt.Rows)
{
string sDate = "";
if(!string.IsNullOrEmpty(row["birthday"].ToString()))
{
sDate = row["birthday"].ToString();
}
string format = "yyyyMMdd";
System.Globalization.CultureInfo provider =CultureInfo.InvariantCulture;
string datetime = DateTime.Now.ToShortDateString();
if (!string.IsNullOrEmpty(sDate))
{
datetime = DateTime.ParseExact(sDate, format, provider).ToShortDateString();
}
if (row["companyname"].ToString().CompareTo("companylogo") != 0)
{
string profile_time = row["profile_timestamp"].ToString();
if (!string.IsNullOrEmpty(profile_time))
{
CSTimeZone time = new CSTimeZone();
profile_time = time.FromUnix(Convert.ToDouble(profile_time)).ToShortDateString()+" "+
time.FromUnix(Convert.ToDouble(profile_time)).ToLongTimeString();
}
string lastUseNetTime = row["last_used_networktime"].ToString();
if (!string.IsNullOrEmpty(lastUseNetTime))
{
CSTimeZone time = new CSTimeZone();
double sec = Convert.ToDouble(lastUseNetTime) * 60;
lastUseNetTime = time.FromUnix(Convert.ToDouble(sec)).ToShortDateString() + " " +
time.FromUnix(Convert.ToDouble(sec)).ToLongTimeString();
}
string lastOnlineTime = row["lastonline_timestamp"].ToString();
if (!string.IsNullOrEmpty(lastOnlineTime))
{
CSTimeZone time = new CSTimeZone();
lastOnlineTime = time.FromUnix(Convert.ToDouble(lastOnlineTime)).ToShortDateString() + " " +
time.FromUnix(Convert.ToDouble(lastOnlineTime)).ToLongTimeString();
}
lst.Add(new CONTACT_INFO()
{
gender=Convert.ToInt32(row["gender"].ToString()),
timezone=row["timezone"].ToString(),
fullName = row["fullname"].ToString(),
profile_timestamp = profile_time,
last_used_networktime = lastUseNetTime,
lastonline_timestamp = lastOnlineTime,
birthday = string.IsNullOrEmpty(sDate) ? "" : datetime
});
}
}
return lst;
}
The function FromUnix is written as
public DateTime FromUnix(double seconds)
{
DateTime datetime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();
return datetime.AddSeconds(seconds);
}
I am pretty sure this is a parsing problem
The following line would throw exceptions if the value of sDate is not in the defined format of yyyyMMdd
datetime = DateTime.ParseExact(sDate, format, provider).ToShortDateString();
I would first use TryParseExact instead of a simple Parse since you do not seem to be using try/catch clauses. It might be a good idea to use the debugger to see exactly where your program is failing.
Other example of potential failures in your code are
double sec = Convert.ToDouble(lastUseNetTime) * 60;
Use double.tryParse
Convert.ToInt32(row["gender"].ToString()
If gender turns out not to be a number another exception will be thrown
etc...

Categories