I have a date value as Fri Feb 15 19:43:05 EST 2013
I could convert it into 2013-02-15 07:43:05 as String.
Now i need to get the date object of this String. I tried using simpleDateFormat in Groovy/Grails but it would just return the original value: Fri Feb 15 07:43:05 EST 2013
The way I am doing it is:
String dateCreated = dateValue.format("yyyy-MM-dd hh:mm:ss")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //required format
Date newDate = sdf.parse(dateCreated)
Can anyone help me?
If you want dates without Time Zone I suggest you to look the Joda-Time API. There's a plugin for Grails.
Look at LocalDate and LocalDateTime, you can construct them passing separated values (year, month, day, hour, second).
If you have a Date instance, you just need:
Date dateValue = ...
String dateCreated = dateValue.format("yyyy-MM-dd hh:mm:ss")
and dateCreated will contain value like 2013-02-15 07:43:05. You don't need to do anything else
Related
How can I get the start of or end of a week in dart? An example is if three days ago was a Monday, and today is a Wednesday, how can I find the start of the week using dart, that is on Monday
You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:
void main() {
final date = DateTime.parse('2019-10-08 15:43:03.887');
print('Date: $date');
print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
UPDATE
Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)
Dart DateTimes have a weekday getter which is 1 for Monday and 7 for Sunday. Using that, I would do:
DateTime mostRecentSunday(DateTime date) =>
DateTime(date.year, date.month, date.day - date.weekday % 7);
to get the most recent Sunday (which is the start of the current week if the week starts on a Sunday), and
DateTime mostRecentMonday(DateTime date) =>
DateTime(date.year, date.month, date.day - (date.weekday - 1));
for the most recent Monday (which is then the start of the current week if the week starts on a Monday).
You can generalize to
/// The [weekday] may be 0 for Sunday, 1 for Monday, etc. up to 7 for Sunday.
DateTime mostRecentWeekday(DateTime date, int weekday) =>
DateTime(date.year, date.month, date.day - (date.weekday - weekday) % 7);
If you are going to be using the results as calendar dates, I'd used DateTime.utc as the constructor instead. (Always use UTC for calendar dates, then you can do day-based arithmetic on them safely).
I'd even consider using DateTime.utc in any case because it avoids any potential issues with a daylight saving that starts at midnight (rare, but with time zones, even unlikely things tend to have happened somewhere at some point).
The way you do this will probably depend on what your app's localization is. If you want to treat Sunday as the start of the week, you would do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay));
If you are treating Monday as the start, then do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay - 1));
MaterialLocalizations
If you're using Dart in Flutter, you can use the MaterialLocalizations class to get the index of the first day of the week (0 = Sunday, 6 = Saturday). This should help you decide which method from above that you should use.
The example given for the firstDayOfWeekIndex property is a good reference:
var localizations = MaterialLocalizations.of(context);
// The name of the first day of week for the current locale.
var firstDayOfWeek = localizations.narrowWeekdays[localizations.firstDayOfWeekIndex];
The MaterialLocalizations class comes with a ton of built in methods to format and display DateTimes.
dateTime: 2021-01-26 11:21:05.429320
formatFullDate: Tuesday, January 26, 2021
formatCompactDate: 01/26/2021
formatMediumDate: Tue, Jan 26
formatShortDate: Jan 26, 2021
formatShortMonthDay: Jan 26
formatMonthYear: January 2021
formatYear: 2021
If none of these fit your needs, you can also use the DateFormat class to specify how the DateTime should be displayed. It's important to note that the DateFormat class indexes days differently where 1 = Monday and 7 = Sunday.
DateFormat.yMMMd().format(new DateTime.now()) // Jan 26, 2021
DateFormat(DateFormat.ABBR_MONTH_DAY).format(now) // Jan 26
DateFormat(DateFormat.WEEKDAY).format(now) // Tuesday
FIRST DAY OF THE WEEK
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
LAST DAY OF THE WEEK
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime
.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
LAST DAY OF THE MONTH
DateTime findLastDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month + 1, 0);
}
FIRST DAY OF THE MONTH
DateTime findFirstDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month, 1);
}
LAST DAY OF THE YEAR
DateTime findLastDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 12, 31);
}
FIRST DAY OF THE YEAR
DateTime findFirstDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 1, 1); }
Dart/Flutter – How to find the first date and the last date of a week
1. Find the first date of the week
/// Find the first date of the week which contains the provided date.
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
2. Find the last date of the week
/// Find last date of the week which contains provided date.
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
Testing
void main() {
// Find first date and last date of THIS WEEK
DateTime today = DateTime.now();
print(findFirstDateOfTheWeek(today));
print(findLastDateOfTheWeek(today));
// Find first date and last date of any provided date
DateTime date = DateTime.parse('2020-11-24');
print(findFirstDateOfTheWeek(date));
print(findLastDateOfTheWeek(date));
}
// Output
2020-11-23 06:54:42.865446
2020-11-29 06:54:42.865446
2020-11-23 00:00:00.000
2020-11-29 00:00:00.000
None of the above worked for me but #JoeMuller gave an interesting piece of info on the material localizations, which led me to find out that for what i want, sunday in date.weekday should be 0 took a while to figure it out many thanks to joe and #julemand101 I have this for UK calendar starting from sunday and ending on saturday
void main() {
final date = DateTime.parse('2021-08-01');
print('Date: $date');
final weekDay = date.weekday == 7 ? 0 : date.weekday;
print('Start of week: ${getDate(date.subtract(Duration(days: weekDay)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - weekDay - 1)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
I have 2 function:
DateTime getStartTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day);
return dateTime.subtract(Duration(days: currentDate.weekday - 1));
}
DateTime getEndTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day, 23, 59, 59, 999);
return dateTime.add(Duration(days: DateTime.daysPerWeek - currentDate.weekday));
}
Below is the code which should work fine in most cases.
We can get start and end of the week like this:-
To get the first day of the week for a date use the below function.
Like Sunday (Also known as 7 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getFirstDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Sunday from the provided date
// By going back a number of weekdays from the current date to reach Sunday
DateTime firstDayOfWeekInUTC;
// If current date is not Sunday subtract days to reach Sunday
if (currentWeekDayInUTC != DateTime.sunday) {
firstDayOfWeekInUTC =
dateTimeInUTC.subtract(Duration(days: currentWeekDayInUTC));
}
// If current date is Sunday use it as the first day of week
else {
firstDayOfWeekInUTC = dateTimeInUTC;
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime firstDayOfWeekInLocal = DateTime(firstDayOfWeekInUTC.year,
firstDayOfWeekInUTC.month, firstDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return firstDayOfWeekInUTC;
} else {
return firstDayOfWeekInLocal;
}
}
To get the last day of the week for a date use the below function.
Like Saturday (Also known as 6 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getLastDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Saturday from the provided date
// By going forward a number of weekdays from the current date to reach Saturday
DateTime lastDayOfWeekInUTC;
// If current date is not Sunday add days enough to reach Saturday
if (currentWeekDayInUTC != DateTime.sunday) {
lastDayOfWeekInUTC = dateTimeInUTC
.add(Duration(days: DateTime.saturday - currentWeekDayInUTC));
}
// If current date is Sunday add days UpTo saturday
else {
lastDayOfWeekInUTC = dateTimeInUTC.add(Duration(days: DateTime.saturday));
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime lastDayOfWeekInLocal = DateTime(lastDayOfWeekInUTC.year,
lastDayOfWeekInUTC.month, lastDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return lastDayOfWeekInUTC;
} else {
return lastDayOfWeekInLocal;
}
}
I need help with a quick question I a string "07/10/2014" how can I get first the year "2014",second the month "10" ,third the day- "07" with out "/" only the values in VB.NET
Please show me the full way how to do it.
First declare it like this Dim x as Date = "07/10/2014". And to get the individual values use x.Day, x.Month and x.Year
Use the DateTime.Parse() method then use the return DateTime structure to extract the Month, Day, Year properties (similar to DJK's answer above).
If the thread's current culture is set to one that understands "mm/dd/yyyy" format, then the code can be as simple as:
Dim dt As DateTime = DateTime.Parse("07/15/2014")
MessageBox.Show(String.Format("Month: {0}; Day: {1}; Year: {2}", dt.Month, dt.Day, dt.Year))
Have a look at this.
Dim MyDate As Date
MyDate = "07/10/2014"
MsgBox(Format(MyDate, "dd")) ' dd gives you day number
MsgBox(Format(MyDate, "MM")) ' MM gives you month number
MsgBox(Format(MyDate, "YYYY")) ' YYYY gives you year number
The full list of date fomatting string could be found here (MSDN)
UPDATE
Use following example to assign to a string variable
Dim DayOfString As String DayOfString
DayOfString = Format(MyDate, "dd")
The data that I have to convert is written as the separate variables "Month", "Day", and "Year".
The data I need to convert for example is:
Month is "July"
Day is "21"
Year is "2013"
Combine it and use DateTime.ParseExact with CultureInfo.InvariantCulture:
Dim dtStr = String.Format("{0} {1} {2}", month, day, year)
Dim dt = Date.ParseExact(dtStr, "MMMM dd yyyy", CultureInfo.InvariantCulture)
Also have a look at: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
If you don't know if the data is valid you should use DateTime.TryParseExact:
Dim dt As DateTime
If Date.TryParseExact(dtStr, "MMMM dd yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, dt) Then
Console.Write("Date is: " & dt.ToShortDateString())
End If
I would first put the date into a string so
Dim dateString as string = string.format({0} {1} {2}, day, month, year)
Where day, month, year reference the variables holding the date values.
Then try
Dim result as DateTime = Convert.ToDateTime(dateString)
I am using the following function to Convert a String variable to a Date. Subtract a day from it and convert the date back to a String. The code goes as follows
Dim edate As String
Dim expenddt As Date
edate = txtenddt.Text
expenddt = Date.ParseExact(edate, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
expenddt = expenddt.AddDays(-1)
Dim asd As String = expenddt.ToString
If edate has a value 29/12/2011 than the value in expenddt gets changed to a different format and the value in expenddt comes to 12/29/2011 and later after subtracting a day expenddt is 12/28/2011 and than when i convert it back to a String i get the value in asd as "12/28/2012 12:00:00 AM"
I have changed the date format on my system to d/M/yyyy in Regional And Language Option in Control Panel but i still get a different format in expenddt
Can anyone explain me why this is happening? How can i keep the format of the date in dd/mm/yyyy e.g 29/12/2011 and after
Subtracting a day it should remain 28/12/2011 and not 12/29/2011
Use Date.ToString() to convert date to string with dd/MM/yyyy format.
Dim asd As String = expenddt.ToString("dd/MM/yyyy")
Just try this:
Dim dateString As String = "Mon 16 Jun 8:30 AM 2008"
Dim format As String = "ddd dd MMM h:mm tt yyyy"
Dim dateTime__1 As DateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture)
hope this may helpful....
I'm trying to convert a string into a date format
My string looks like this
Dim MyString as String = "June 2011"
And I'm trying to convert it like this
Convert.ToDateTime(MyString).ToString("MM yyyy")
But it's giving me the error
Syntax error converting datetime from
character string.
The desired output would be either 06/2011 or 01/06/2011. The value of my string will only ever have the month and year in though.
Any ideas?
A datetime object in .NET represents one single point in time. To create one from a Gregorian calendar date, you need all three parts (day, month, year), otherwise it can't represent one single point in time.
Since your business requirement is to assume that the day number is 1 if not provided, just insert that number into the string before parsing.
Dim myDate As Date = Convert.ToDateTime("1 " & MyString)
EDIT:
Sorry, forgot to mention that string manipulations like that are of course culture-dependent. You don't mention what culture you are in. "June 2011" can imply either en-GB or en-US. Since inserting the day number at the start of the string is easier than trying to insert it between the month and year, I suggest you go for something like this.
Dim myDate1 As Date = Date.Parse("1 " & myString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.AllowWhiteSpaces)
Convert.ToDateTime() only takes the full date so try prepending 01 as the day first i.e.
Convert.ToDateTime("01 " + MyString)
DateTime.Parse(MyString).ToString("MM yyyy")
This worked for me
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
Dim MyString As String
Dim d As DateTime = DateTime.Now 'test start
'test all Month Year strings
For x As Integer = 1 To 12
MyString = d.ToString("MMMM yyyy") 'convert date to March 2011 then April 2011 then...
Dim dt As DateTime = DateTime.ParseExact(MyString, "MMMM yyyy", provider)
Debug.WriteLine(MyString & " " & dt.ToString)
d = d.AddMonths(1)
Next