How to get the current time in Jerusalem with C#? - c#

I need to know Jerusalem Current time.
That code taking server time but I need Jerusalem time:
DateTime currentTime = DateTime.Now;
dayName = currentTime.DayOfWeek;
Edit:
with help of Vinoth answer(I took only the AddHours(2) part) it should be like that (not works):
DateTime currentTime = DateTime.Now;
currentTime=currentTime.AddHours(2);//Jerusalem Time
dayName = currentTime.DayOfWeek;
Edit2:my improvement (ToUniversalTime())
DateTime currentTime = DateTime.Now;
currentTime=currentTime.ToUniversalTime().AddHours(2);//Jerusalem Time
dayName = currentTime.DayOfWeek;

This will help you. I have used this is one of my app. Jus pasting the code
public static DateTime GetIsraelTime(DateTime d) {
d = d.AddHours(2); // Israel is at GMT+2
// April 2nd, 2:00 AM
DateTime DSTStart = new DateTime(d.Year, 4, 2, 2, 0 ,0);
while (DSTStart.DayOfWeek != DayOfWeek.Friday)
DSTStart = DSTStart.AddDays(-1);
CultureInfo jewishCulture = CultureInfo.CreateSpecificCulture("he-IL");
System.Globalization.HebrewCalendar cal =
new System.Globalization.HebrewCalendar();
jewishCulture.DateTimeFormat.Calendar = cal;
// Yom HaKipurim, at the start of the next Jewish year, 2:00 AM
DateTime DSTFinish =
new DateTime(cal.GetYear(DSTStart)+1, 1, 10, 2, 0 ,0, cal);
while (DSTFinish.DayOfWeek != DayOfWeek.Sunday)
DSTFinish= DSTFinish.AddDays(-1);
if (d>DSTStart && d<DSTFinish)
d = d.AddHours(1);
return (d);
}

var israelTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Israel Standard Time")
Complete time zones ids list can be found here.

Related

Return month names from current month

I need help in C# getting month names from current month, meaning user inputs a month(name) and will return the list of months from the starting month until the current month.
Example; user inputs "August" and current month is "December" so it should return "August, September, October, November, December".
I've done a few steps but still can't get to it.
1st try:
string pattern = ("MMMM/yyyy");
Console.WriteLine("Enter Month: MMMM/yyyy");
DateTime inpMonth = DateTime.ParseExact(Console.ReadLine(),pattern,System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
string last = inpMonth.ToString("MMMM/yyyy");
DateTime date = DateTime.Now;
string curr = date.ToString("MMMM/yyyy");
2nd Try(new step):
//First Date
DateTime 1Date = new DateTime(2020, 12, 01);
//Second Date
DateTime 2Date =new DateTime(2019, 01, 01);
int month1 = (2Date.Month - 1Date.Month);
int month2 = (2Date.Year - 1Date.Year) * 12;
int months = month1 + month2;
string mon = months.DateTime.ToString("MMMM"); //trying to convert the month number to month name
Both try seems to not get any close result..
The following code will output to the result you requested:
var start = "August";
var today = DateTime.Today;
var date = new DateTime(today.Year, DateTime.ParseExact(start, "MMMM", CultureInfo.CurrentCulture).Month, 1);
while (date < today)
{
Console.WriteLine($"{date:MMMM}");
date = date.AddMonths(1);
}

Days between two dates in asp.net

I find the number of days between the date of the employee's employment and the date of the day, and multiply by the daily amount. The only complaint is that when I find out the number of days between two dates, it calculates over 31 days for the months that draw 31 days naturally. I need to trade over 30 days while I get the dates between two dates.
How can I do that?
Do you want something like this?
DateTime date1 = new DateTime(2016, 10, 3);
DateTime date2 = new DateTime(2016, 11, 3);
var numberOfDays = date2.Subtract(date1).TotalDays;
I Hope this is what you wanted:
DateTime firstDay = DateTime.ParseExact("2016-10-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime lastDate = DateTime.ParseExact("2016-11-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
double daysBetween = (lastDate - firstDay).TotalDays;
if you are just interested in full month, you can use following code
var normalisedDays = ((lastDate.Year - firstDate.Year) * 12 + lastDate.Month - firstDate.Month) * 30;
in Controll :
DateTime Date_1 = Date_Start;
DateTime Date_2 = Date_End;
TimeSpan difference = Date_2 - Date_1 ;
var days = difference.TotalDays;
in Script :
<script>
function calculateDifference()
{
var Date_Start= document.getElementById("Date_Start").value;
var Date_End= document.getElementById("Date_End").value;
var Date_StartSplit = Date_Start.split("/");
var Date_EndSplit = Date_End.split("/");
var StartDate = new Date(Date_StartSplit[2], Date_StartSplit[0] - 1, Date_StartSplit[1]);
var EndDate = new Date(Date_EndSplit[2], Date_EndSplit[0] - 1, Date_EndSplit[1]);
var res = Math.abs(StartDate - EndDate) / 1000;
var days = Math.floor(res / 86400);
document.getElementById("Nombre_days").value = days;
}
</script>

C# datetime scope

Assuming I can not change service that returns data, I am left with
var date = "20140231";
var scope = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);
Clearly "20140231" is lazy way of saying end of February. What is the cleanest way to get last date of February with input of "20140231"?
There is 1 constraint - this should work with .net 2.0.
string date = "20140231";
DateTime result;
int year = Convert.ToInt32(date.Substring(0, 4));
int month = Convert.ToInt32(date.Substring(4, 2));
int day = Convert.ToInt32(date.Substring(6, 2));
result = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));
February can have only 28 or 29 days depends on current year is a leap year or not.
It can't have 30 or 31 days in any year. That's why you can't parse your 20140231 string successfully.
You can clearly get the last day of February like;
DateTime lastDayOfFebruary = (new DateTime(2014, 2, 1)).AddMonths(1).AddDays(-1);
If your service always get year as a first 4 character, you can use .Substring() to get year and pass DateTime constructor as a year.
var date = "20140231";
string year = date.Substring(0, 4);
DateTime lastDayOfFebruary = (new DateTime(int.Parse(year), 2, 1)).AddMonths(1).AddDays(-1);
You could create a while, cut the date in pieces, and keep subtracting one from the day part until it is a valid date. This should really be fixed on the entry side though.
Try this:
var date = "20140231";
DateTime scope;
bool dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
while (!dateValid)
{
string yearMonth = date.Substring(0, 4);
int day = Convert.ToInt32(date.Substring(6, 2));
if (day > 1)
{
day--;
}
else
{
break;
}
date = yearMonth + day.ToString().PadLeft(2, '0');
dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
}

How do I find week numbers of a given date range in C#

I need to find the week numbers of a given date rage in C#.
Ex: date between 01/01/2014 and 14/01/2014
Week numbers are 1st,2nd and 3rd weeks, likewise.
Thanks.
Not the smartest way, but works!
var d1 = new DateTime(2014, 1, 1);
var d2 = new DateTime(2014, 1, 14);
var currentCulture = CultureInfo.CurrentCulture;
var weeks = new List<int>();
for (var dt = d1; dt < d2; dt =dt.AddDays(1))
{
var weekNo = currentCulture.Calendar.GetWeekOfYear(
dt,
currentCulture.DateTimeFormat.CalendarWeekRule,
currentCulture.DateTimeFormat.FirstDayOfWeek);
if(!weeks.Contains(weekNo))
weeks.Add(weekNo);
}
This should work:
public List<int> Weeks(DateTime start, DateTime end)
{
List<int> weeks=new List<int>();
var Week=(int)Math.Floor((double)start.DayOfYear/7.0); //starting week number
for (DateTime t = start; t < end; t = t.AddDays(7))
{
weeks.Add(Week);
Week++;
}
return weeks;
}
All this does is get the week of the start date, then loops through one week at a time until you get to the end date, incrementing the week and adding it to the list of weeks.
OK, let's start with a simple, unoptimized example. We'll simply examine every date between those dates and check what week of the year it is.
We can do that with a simple loop:
var end = new DateTime(2014, 1, 14);
for (var date = new DateTime(2014, 1, 1); date <= end; date = date.AddDays(1))
{
}
This will simply loop over every day between two dates. Now we need to examine those days to determine their day of week. To do this you need to consider a few things: What is the first day of a week? Sunday? Monday? Are we assuming gregorian calendar?
For our example, let's assume the first day of the week is a Sunday and we are indeed using the Gregorian calendar. Then we will check each date, and keep a list of unique weeks of the year using a HashSet:
var weekNumber = new HashSet<int>();
var end = new DateTime(2014, 1, 14);
var calendar = new GregorianCalendar();
for (var date = new DateTime(2014, 1, 1); date <= end; date = date.AddDays(1))
{
weekNumber.Add(calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday));
}
The weekNumber Hashset now contains the weeks of the year.
Is this optimized? No. It checks far more dates than it needs to, but the implementation is simple and fast enough. Optimizing can be done as a separate task.
Easy. Here's the code that determines the week of the year for a single date. This should get you going:
int WeekOfYear(DateTime date, DayOfWeek dayOfWeekStart) {
//Find the first day of the year that's the start of week day. If it's not 1/1,
//then we have a first partial week.
bool firstPartialWeek = false;
DateTime firstFullWeekStart = new DateTime(date.Year, 1, 1);
while(firstFullWeekStart.DayOfWeekDay != dayOfWeekStart) {
firstFullWeekStart = firstOfWeek.AddDays(1);
firstPartialWeek = true;
}
//Return the week by integer dividing the date difference by seven,
//and adding in the potential first partial week
return (firstPartialWeek ? 1 : 0) + ((date - firstFullWeekStart).TotalDays / 7);
}

Getting first and last day of the current month

I have here 2 datepicker for start date and end date.
how can I get the first day and last day of the current month
rdpStartDate.SelectedDate = DateTime.Now;
rdpEndDate.SelectedDate = DateTime.Now;
DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);
You could also use DateTime.DaysInMonth method:
var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);
That should give you what you need.
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by #Jade
Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.
var now = DateTime.Now; // get the current DateTime
//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month);
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1);
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);
//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay;
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

Categories

Resources