Get week of month with Joda-Time - datetime

Is it possible to parse a date and extract the week of month using Joda-Time. I know it is possible to do it for the week of year but I cannot find how/if it is possible to extract the week of month.
Example: 2014-06_03 where 03 is the third week of this month
DateTime dt = new DateTime();
String yearMonthWeekOfMonth = dt.toString("<PATTERN for the week of month>");
I have tried the pattern "yyyyMMW" but it is not accepted.

Current joda-time version doesn't support week of month, so you should use some workaround.
1) For example, you can use next method:
static DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM_'%d'");
static String printDate(DateTime date)
{
final String baseFormat = FORMATTER.print(date); // 2014-06_%d
final int weekOfMonth = date.getDayOfMonth() % 7;
return String.format(baseFormat, weekOfMonth);
}
Usage:
DateTime dt = new DateTime();
String dateAsString = printDate(dt);
2) You can use Java 8, because Java's API supports week of month field.
java.time.LocalDateTime date = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM_W");
System.out.println(formatter.format(date));

This option in Joda is probably nicer:
Weeks.weeksBetween(date, date.withDayOfMonth(1)).getWeeks() + 1

For the case you don't like calculations so much:
DateTime date = new DateTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date.toDate());
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);

If the start day of week is Monday then you can use it:
public int getWeekOfMonth(DateTime date){
DateTime.Property dayOfWeeks = date.dayOfWeek();
return (int) (Math.ceil((date.dayOfMonth().get() - dayOfWeeks.get()) / 7.0)) + 1;
}

Related

Difference Between Two localDate

I have a date returned by a json, it is in the following variable as string:
val dateEvent = "2019-12-28 21:00:00"
The calculation I need is to know how many days hours minutes are left with the current date.
I have found some solutions but these use as input "2019-12-28" and I have my format with the time included.
java.time
Since Java 9 you can do (sorry that I can write only Java code):
DateTimeFormatter jsonFormatter = DateTimeFormatter.ofPattern("u-M-d H:mm:ss");
String dateEvent = "2019-12-28 21:00:00";
Instant eventTime = LocalDateTime.parse(dateEvent, jsonFormatter)
.atOffset(ZoneOffset.UTC)
.toInstant();
Duration timeLeft = Duration.between(Instant.now(), eventTime);
System.out.format("%d days %d hours %d minutes%n",
timeLeft.toDays(), timeLeft.toHoursPart(), timeLeft.toMinutesPart());
When I ran the code just now, the output was:
145 days 4 hours 19 minutes
In Java 6, 7 and 8 the formatting of the duration is a bit more wordy, search for how.
Avoid SimpleDateFormat and friends
The SimpleDateFormat and Date classes used in the other answer are poorly designed and long outdated. In my most honest opinion no one should use them in 2019. java.time, the modern Java date and time API, is so much nicer to work with.
Use the following function:
fun counterTime(eventtime: String): String {
var day = 0
var hh = 0
var mm = 0
try {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val eventDate = dateFormat.parse(eventtime)
val cDate = Date()
val timeDiff = eventDate.time - cDate.time
day = TimeUnit.MILLISECONDS.toDays(timeDiff).toInt()
hh = (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day.toLong())).toInt()
mm =
(TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff))).toInt()
} catch (e: ParseException) {
e.printStackTrace()
}
return if (day == 0) {
"$hh hour $mm min"
} else if (hh == 0) {
"$mm min"
} else {
"$day days $hh hour $mm min"
}
}
counterTime(2019-08-27 20:00:00)
This returns 24 days 6 hour 57 min
Note: The event date should always be a future date to the current date.

how to convert any string formatted date to datetime variable.?

domaindate.Text="31-03-3015";
DateTime dt = DateTime.Parse(domaindate.Text);
int day = dt.Day;
int month = dt.Month;
int year = dt.Year;
if (ddlyear.SelectedItem.Text == "1")
{
year = year + 1;
month = month - 1;
edate = String.Join("/", day, month, year);
}
p.expirydate = Convert.ToDateTime(edate);
Where p.expiredate id DateTime Property variable.
Geting Error:String was not recognized as a valid DateTime.
So, How i convert it to dd/MM/yyyy.?
Use the ParseExcact Method with the string format.
p.expirydate =DateTime.ParseExact(edate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
EDIT:
If you want add days to a specific date use the AddDays() Method
DateTime dt= DateTime.Parse(domaindate.Text);
p.expirydate = today.AddDays(number of days you want);

Difference in years,months and days between 2 hijri dates

Please can anyone provide a method to calculate the difference between 2 hijri dates thanks in advance
i tried this code
HijriCalendar hijriCal=new HijriCalendar();
DateTimeFormatInfo DTFormat = new System.Globalization.CultureInfo("ar-sa", false).DateTimeFormat;
DTFormat.Calendar = new System.Globalization.HijriCalendar();
DTFormat.ShortDatePattern = "dd/MM/yyyy";
string HijriDate = FromDate.Date.ToString("d", DTFormat);
string[] fromDateParams=HijriDate.Split('/');
HijriDate = ToDate.Date.ToString("d", DTFormat);
string[] toDateParams = HijriDate.Split('/');
DateTime fromDateHijri = new DateTime(hijriCal.GetYear(FromDate), hijriCal.GetMonth(FromDate), int.Parse(fromDateParams[0]), hijriCal);
DateTime toDateHijri = new DateTime(hijriCal.GetYear(ToDate), hijriCal.GetMonth(ToDate), int.Parse(toDateParams[0]), hijriCal);
TimeSpan ts = ToDate.Subtract(FromDate);
As long as you just store the dates in normal datetimes, just treat them as any other date.
public TimeSpan GetDifference(this DateTime date1, DateTime date2) {
if (date1 < date2) {
return date2 - date1;
}
else if (date1 > date2) {
return date1 - date2;
}
return new TimeSpan(0);
}

int to string to date

i use asp.net
i have a int (10112009)
in the end i want a date formate like day- day / month month / yyyy
what's the best way (or a way) to do that?
thanks
I would do something like this:
int n = 10112009;
DateTime date;
if (DateTime.TryParseExact(n.ToString("00000000"), "ddMMyyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// use date
}

To calculate days in a month

i have a textbox that displays date in format,for eg:March,20,2008.Then i need to get total days n march in year 2008.Can anybody help
You can use the DaysInMonth function
e.g.
Date.DaysInMonth(2008, 3)
Obviously, you'll have to pass the year and month to the function
int year = DateTime.Now.Year;
int month = DateTime.Now.Month;
int numDays = DateTime.DaysInMonth(year, month);
Use DataTime.DaysInMonth()
http://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth(VS.71).aspx
Remember to use the date they entered.
VB Code:
dim enteredDate as DateTime = cdate(txtDateBox.text)
dim daysInMonth as Int = DateTime.DaysInMonth(enteredDate.year,enteredDate.month)

Resources