Hi Friends đź‘‹,
Welcome To Infinitbility! ❤️
To convert string to date in moment js, just use the moment().format()
method by passing desire format string parameters.
Just import moment in your file and invoke moment().format('DD-MM-YYYY');
it will show the current date time plus 30 years.
moment().format('DD-MM-YYYY')
Today, I’m going to show How do I convert string to date in moment js, here I will use the momentjs common method format()
to convert string to the date object.
Let’s start the today’s tutorial How do you convert string to date in moment js?
Table of content
- Installation
- Moment Format rules
- Example in reactjs
Installation
Use the below installation command as per your package manager, moment support npm, Yarn, NuGet, spm, and meteor.
npm install moment --save # npm
yarn add moment # Yarn
Install-Package Moment.js # NuGet
spm install moment --save # spm
meteor add momentjs:moment # meteor
Moment Format rules
Moment follow below rules to format date time as per user requirement like show am, pm in time string, show two digits year, and show date with st
, nd
, and rd
.
Input | Example | Description |
---|---|---|
YYYY | 2014 | 4 or 2 digit year. Note: Only 4 digit can be parsed on 'strict' mode |
YY | 14 | 2 digit year |
Y | -25 | Year with any number of digits and sign |
Q | 1..4 | Quarter of year. Sets month to first month in quarter. |
M MM | 1..12 | Month number |
MMM MMMM | Jan..December | Month name in locale set by moment.locale() |
D DD | 1..31 | Day of month |
Do | 1st..31st | Day of month with ordinal |
DDD DDDD | 1..365 | Day of year |
H HH | 0..23 | Hours (24 hour time) |
h hh | 1..12 | Hours (12 hour time used with a A.) |
k kk | 1..24 | Hours (24 hour time from 1 to 24) |
a A | am pm | Post or ante meridiem (Note the one character a p are also considered valid) |
m mm | 0..59 | Minutes |
s ss | 0..59 | Seconds |
After reading the above rules, you can easily understand how to format time as per your requirement. let’s see how we can use the format()
method with the above rules.
Example in reactjs
In the following example, we are going to do
- import the moment package
- example of show date using date string
- example of show date time using date string
let’s write the code.
import moment from "moment";
function App() {
return (
<div>
{/* example of show date using date string */}
{console.log(moment('2012-02-27T10:00:00').format("DD-MM-YYYY"))}
{console.log("----")}
{/* example of show date time using date string */}
{console.log(moment('2012-02-27T10:00:00').format("DD-MM-YYYY h:mm:ss a"))}
</div>
);
}
export default App;
In the above program, we call moment().format()
with date string and format string.
let’s check the output.
I hope it’s help you, All the best đź‘Ť.