I'm using currently moment.js (moment-with-locales.js - v.2.14.1) in my project. I want to remove the time of my datetime string to get only the date. But if I use the .format() method of moment.js I got an incorrect date.
I want to format this datetime string:
from ' 08.10.2016 11:00 ' to ' 08.10.2016 '
Here is a snipped that I used in my angular project:
var date = moment('08.10.2016 11:00').format('DD.MM.YYYY')
console.log(date)
If I run this I got this output
10.08.2016
instead of
08.10.2016
The funny thing is, if I want to get the timestamp (milliseconds) of my datetime string, it works perfect. Example:
var dateStart = moment('08.10.2016 19:00', 'DD.MM.YYYY HH:mm').valueOf()
console.log(dateStart)
Will return
1475946000000 -> Sat Oct 08 2016 19:00:00 GMT+0200
How can I get the correct Date?
It depends on your locale. en-US locate means moment will parse by "month day year". So, you need to parse with the pattern as well:
var date = moment('08.10.2016 11:00','DD.MM.YYYY HH:mm').format('DD.MM.YYYY')
Related
I am trying to convert datetime value from this format Wed Mar 9 09:48:09 PST 2016 into the following format YYYY-MM-DD HH:mm:ss
I tried to use moment but it is giving me a warning.
"Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Arguments: [object Object]
fa/<#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:9493
ia#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:10363
Ca#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15185
Ba#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15024
Aa#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:14677
Da#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15569
Ea#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15610
a#http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:41
#http://localhost:1820/Home/Test:89:29
jQuery.event.dispatch#http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:5225:16
jQuery.event.add/elemData.handle#http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:4878:6
"
according to https://github.com/moment/moment/issues/1407 I should not be trying to use moment() to do this since it is not reliable.
How can I reliably convert the Wed Mar 9 09:48:09 PST 2016 into the following format YYYY-MM-DD HH:mm:ss?
You could try using Date.toJSON() , String.prototype.replace() , trim()
var date = new Date("Wed Mar 9 09:48:09 PST 2016").toJSON()
.replace(/(T)|(\..+$)/g, function(match, p1, p2) {
return match === p1 ? " " : ""
});
console.log(date);
Since you tagged your question with moment, I'll answer using moment.
First, the deprecation is because you are parsing a date string without supplying a format specification, and the string is not one of the standard ISO 8601 formats that moment can recognize directly. Use a format specifier and it will work just fine.
var m = moment("Wed Mar 9 09:48:09 PST 2016","ddd MMM D HH:mm:ss zz YYYY");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // "2016-03-09 09:48:09"
Secondly, recognize that in the above code, zz is just a placeholder. Moment does not actually interpret time zone abbreviations because there are just too many ambiguities ("CST" has 5 different meanings). If you needed to interpret this as -08:00, then you'd have to do some string replacements on your own.
Fortunately, it would appear (at least from what you asked) that you don't want any time zone conversions at all, and thus the above code will do the job.
I'm working on a JavaScript application. I have two different String dates 31/10/2013 and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );
31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013
1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013
You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)
and all the documentation on http://www.w3schools.com/js/js_obj_date.asp
31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."
If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();
Else, you can always welcome to split and rebuild the date object.
I have a string in this format:
var testDate = "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
I would like to use Moment.js get it in this format mm/dd/yyyy : 04/12/2013 for display.
I tried to do it using this method,
moment(testDate,'mm/dd/yyyy');
Which errors and says there is no such method called replace? Am I approaching this in the wrong way?
Edit
I should also mention that I am using a pre-packaged version of Moment.js, packaged for Meteor.js
Object [object Date] has no method 'replace' : The Exact error from the console
Stack Trace:
at makeDateFromStringAndFormat (http://127.0.0.1:3000/packages/moment/lib/moment/moment.js?b4e3ac4a3d0794023a4410e7941c3e179398b5b0:539:29)
at moment (http://127.0.0.1:3000/packages/moment/lib/moment/moment.js?b4e3ac4a3d0794023a4410e7941c3e179398b5b0:652:24)
at populateProfileForEdit (http://127.0.0.1:3000/client/views/home/administration/directory/profiles/profiles.js?acfff908a6a099f37312f62892a22b40f82e5e0f:147:25)
at Object.Template.profile_personal.rendered (http://127.0.0.1:3000/client/views/home/administration/directory/profiles/profiles.js?acfff908a6a099f37312f62892a22b40f82e5e0f:130:13)
at Spark.createLandmark.rendered (http://127.0.0.1:3000/packages/templating/deftemplate.js?b622653d121262e50a80be772bf5b1e55ab33881:126:42)
at http://127.0.0.1:3000/packages/spark/spark.js?45c746f38023ceb80745f4b4280457e15f058bbc:384:32
at Array.forEach (native)
at Function._.each._.forEach (http://127.0.0.1:3000/packages/underscore/underscore.js?867d3653d53e9c7a171483edbcad9670e12288c7:79:11)
at http://127.0.0.1:3000/packages/spark/spark.js?45c746f38023ceb80745f4b4280457e15f058bbc:382:7
at _.extend.flush (http://127.0.0.1:3000/packages/deps/deps.js?9642a93ae1f8ffa8eb1c2475b198c764f183d693:231:11)
The 2nd argument to moment() is a parsing format rather than an display format.
For that, you want the .format() method:
moment(testDate).format('MM/DD/YYYY');
Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.
Include moment.js and using the below code you can format your date
var formatDate= 1399919400000;
var responseDate = moment(formatDate).format('DD/MM/YYYY');
My output is "13/05/2014"
moment().format(); // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA"); // "Mon, 5PM"
You Probably Don't Need Moment.js Anymore
Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.
date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).
Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.
import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)
Format date with date-fns:
// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"
// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"
More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs
var moment = require('moment');
let yourdate = '2021-01-02T07:57:45.121Z'; // for example
moment(yourdate).format('MM/DD/YYYY');
// output : 01-02-2021
moment(yourdate).format('DD-MMM-YYYY');
// output : 01-Jan-2021
For fromating output date use format. Second moment argument is for parsing - however if you omit it then you testDate will cause deprecation warning
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format...
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
let s= moment(testDate).format('MM/DD/YYYY');
msg.innerText= s;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div id="msg"></div>
to omit this warning you should provide parsing format
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
let s= moment(testDate, 'ddd MMM D YYYY HH:mm:ss ZZ').format('MM/DD/YYYY');
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
You can pass "L" to format method, which handles internationalisation...
moment.locale('en-US');
moment().format("L");
> "06/23/2021"
moment.locale('fr');
moment().format("L");
> "23/06/2021"
Other long date formats (fr locale):
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
Docs: https://momentjs.com/docs/#/displaying/format/ (see "Localized formats")
To get the current UTC time in YYYY-MM-DD HH:MM:ss.Millisecond with timezone using moment format as below
moment().utc().format('Y-MM-DD HH:mm:ss.SSS Z').
Output
2022-09-20 15:28:39.446 +0000
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly.
Please find the code:
I am using moment.js format function on a current date as (today is 29-06-2020)
var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement :
new Date(startDate)
The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result.
And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE.
For clear understanding please find my question in the link:
Date went wrong when using Momentjs date format in IE 11
I've inherited a project for a company I'm working for. Their dates are recorded in the following format:
March 18th, 2011 would be listed as "18 Mar 2011".
April 31st, 2010 would be listed as "31 Apr 2010".
How would I use Javascript to add one day to a date formatted in the above manner, then reconvert it back into the same format?
I want to create a function that adds one day to "18 Mar 2011" and returns "19 Mar 2011". Or adds 1 day to "30 Jun 2011" and returns "1 Jul 2011".
Can anyone help me out?
First of all there is no 31st of April ;)
To the actual issue, the date object can understand the current format when passed as an argument..
var dateString = '30 Apr 2010'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1); // create new increased date
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).substr(-2) + ' ' + newDate.toDateString().substr(4,3) + ' ' + newDate.getFullYear();
alert(newDateString);
demo at http://jsfiddle.net/gaby/jGwYY/1/
The same extraction using (the better supported) slice instead of substr
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).slice(-2) + ' ' + newDate.toDateString().slice(4,7) + ' ' + newDate.getFullYear();
Demo at http://jsfiddle.net/jGwYY/259/
You would want to convert the date string into a Date object, add one day to the object, and then convert back. Please have a look at the API docs for Date as a starting point.
Most (all?) browsers will be able to parse that date string in with a simple
var parsedDate = new Date(dateString);
Once you have a Date object you can add a day and output a formatted date string using something like underscore.date.
If you discover that some browsers can't parse that date format then you can write a pretty simple regex that will pull apart the date string into its constituent parts, and then build a Date instance by hand.
Also I would strongly recommend doing the parsing in a separate function, and to try and keep dates in a Date representation as much as possible. Parse the string into a date as soon as you can, and format it back into a string as late as you can.
How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?
Many different date formats can be converted to date objects just by passing them to the Date() constructor:
var date = new Date(datestring);
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
If the date formats you're receiving are consistent, you can fix them up this way:
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
I'd use the Datejs library's parse method.
http://www.datejs.com/
I tried your example and it worked fine...
5/27 11:00pm
Wednesday, May 27, 2009 11:00:00 PM
I have used the Dojo time parser to do things like this:
Check it out:
http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse
Not the cleanest, but works:
var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');
function ConvertDate(strWeirdDate, strYear)
{
strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
return new Date(strWeirdDate);
}
Probably want to trim the string first as well.
Just another option, which I wrote:
DP_DateExtensions Library
It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.
Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.