Created
March 21, 2022 14:25
-
-
Save ayoubzulfiqar/30b2e2e01406ef8fb83c22f74b10657f to your computer and use it in GitHub Desktop.
This is the snippet for to get date and time without using any external libraries such as Intl. which is not bad to use but this snippet is perfect for o get date and time or sometime jsut date. Much better than using library.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define a simple format function from scratch | |
String dateTimeformat({required DateTime time, bool dateOnly = false}) { | |
String year = time.year.toString(); | |
// Add "0" on the left if month is from 1 to 9 | |
String month = time.month.toString().padLeft(2, '0'); | |
// Add "0" on the left if day is from 1 to 9 | |
String day = time.day.toString().padLeft(2, '0'); | |
// Add "0" on the left if hour is from 1 to 9 | |
String hour = time.hour.toString().padLeft(2, '0'); | |
// Add "0" on the left if minute is from 1 to 9 | |
String minute = time.minute.toString().padLeft(2, '0'); | |
// Add "0" on the left if second is from 1 to 9 | |
String second = time.second.toString(); | |
// If you only want year, month, and date | |
if (dateOnly == false) { | |
return "$year-$month-$day $hour:$minute:$second"; | |
} | |
// return the "yyyy-MM-dd HH:mm:ss" format | |
return "$year-$month-$day"; | |
} | |
// Test our function | |
// void main() { | |
// DateTime currentTime = DateTime.now(); | |
// // Full date and time | |
// final result1 = dateTimeformat(time: currentTime); | |
// print(result1); | |
// // Date only | |
// final result2 = dateTimeformat(time: currentTime, dateOnly: true); | |
// print(result2); | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment