Format existing date variable with moment.js - javascript

I have a date variable (coming from an external source):
var date = '28/04/2017';
var time = '19:28';
It is possible to format these variables with moment.js (or without?) to variout formats?
Example: 04.28 19:28, 2017.04.28 19:28 or even Today at 19:28 (with moment().calendar();)
I tried
moment(date+' '+time).format('MM.DD.YYYY');
...but I am getting "Invalid date" error.

You're using moment(String) method, but you're not passing a Supported
format that it expects to parse.
You should use moment(String, String), where the first String is the input date string, and second is the format of your input date String.
Try this:
moment(date+' '+time,'DD/MM/YYYY HH:mm').format('MM.DD.YYYY');

Try:
moment(new Date(date + ' ' + time)).format('MM.DD.YYYY');

You need to keep the same format:
var date = '04-28-2017'; // Month/day/year
var time = '19:28';
console.log( moment(date, 'MM-DD-YYYY').format('MMMM D') ) // April 28

Related

JavaScript new Date('22/22/2222') convert to a valid date in IE 11

var checkDate = new Date("22/22/2222");
When I check in IE 11 it convert to Wed Oct 22 00:00:00 EDT 2223 so my next line fails
if (checkDate != 'Invalid Date')
How to fix it?
As you've passed in an invalid date format (as far as the ECMA spec is concerned), the browser is free to choose to interpret it how it wishes. It seems IE thinks it can deal with it:
The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
If you're going to pass in strange formats, you're either going to need to validate them yourself or use a library that can do so better than the browsers can.
Months and days can "wrap" in JavaScript. One way to test if the date is legal is to see if the output date corresponds to the original input string. If it doesn't, then it wrapped.
function check(inputString) {
var checkDate = new Date(inputString);
// Get month, day, and year parts, assuming
// you don't have them already
var arr = inputString.split('/');
var isMonthWrapped = +arr[0] !== checkDate.getMonth() + 1;
var isDayWrapped = +arr[1] !== checkDate.getDate();
var isYearWrapped = +arr[2] !== checkDate.getFullYear();
console.log("Parts", +arr[0], +arr[1], +arr[2]);
console.log("Results", checkDate.getMonth() + 1, checkDate.getDate(), checkDate.getFullYear());
console.log("Wrapped?", isMonthWrapped, isDayWrapped, isYearWrapped);
var isLegal = checkDate !== 'Invalid Date' && !isMonthWrapped && !isDayWrapped && !isYearWrapped;
document.body.innerHTML += inputString + ': ' + (isLegal ? 'Legal' : 'Illegal') + '<br>';
};
check("22/22/2222");
check("12/12/2222");
I think that moment.js http://momentjs.com/ is a complete and good package about dates.
You could add string date and format.
moment("12/25/1995", "MM/DD/YYYY");
And you could check if date is valid.
moment("not a real date").isValid();
See documentation
http://momentjs.com/docs/#/parsing/string-format/
You should break up your string and parse Each date to integers individually. It will be much safer.
Do something like this
var dateString = "22/22/2222";
dateString.indexOf("/");
var day = parseInt(dateString.slice(0,dateString.indexOf("/")));
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var month = parseInt(dateString.slice(0,dateString.indexOf("/")))
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var year = parseInt(dateString);
console.log(day, month, year);
var date = new Date(0);
if(month>12) console.log("hey this is totally not a valid month maaaan!")
date.setDate(day);
date.setMonth(month);
date.setYear(year);
console.log(date);

Changing date format javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

Date formatting in moment.js , weird date values

So I have 2 kinds of date coming from json.
m = '201811';
n = '/Date(1433030400000)/';
I am trying to use moment.js to format time, but I can not find appropriate methods for it I guess.
moment(m).format('YYYY DD') //"201811 01"
and the n value I can not understand it leads to this output :
moment(m).format('YYYY DD')//"2015 31"
When you pass a date to moment() constructor, you might have to specify in what format it is.
So for the first date you would need to do:
moment(m, 'YYYYMM').format('YYYY MM'); // if the date is indeed in the form YYYYMM
For the second date, just extract the numeric part from the string and feed it to moment:
var ts = n.match(/(\d+)/);
moment(+ts[1]).format('YYYY DD');
See the snippet:
var m = '201811';
var n = '/Date(1433030400000)/';
alert(moment(m, 'YYYYMM').format('YYYY MM'));
var ts = n.match(/(\d+)/);
moment(+ts[1]).format('YYYY DD');
alert(moment(+ts[1]).format('YYYY MM'));
<script src="http://momentjs.com/downloads/moment.js"></script>
EDIT:
thanks to #MattJohnson, if you have at least moment version 1.3.0, you can simply pass the string in the form /Date(1433030400000)/ to the moment() constructor, and it will automatically detect the proper format, see also here.
Just pass them to moment in the following format:
var m = '201811';
var n = '/Date(1433030400000)/';
var formattedM = window.moment(m, 'YYYYMM').format('YYYY MMM DD'); //2018 Nov 01
var formattedN = window.moment(n).format('YYYY MMM DD'); //2015 May 31
I've dropped an example into jsbin.
Thanks to Matt Johnson for pointing out that moment can take the /Date(1433030400000)/ format.

from unix timestamp to datetime

I have something like /Date(1370001284000+0200)/ as timestamp. I guess it is a unix date, isn't it? How can I convert this to a date like this: 31.05.2013 13:54:44
I tried THIS converter for 1370001284 and it gives the right date. So it is in seconds.
But I still get the wrong date for:
var substring = unix_timestamp.replace("/Date(", "");
substring = substring.replace("000+0200)/", "");
var date = new Date();
date.setSeconds(substring);
return date;
Note my use of t.format comes from using Moment.js, it is not part of JavaScript's standard Date prototype.
A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.
The presence of the +0200 means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.
If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:
var t = new Date( 1370001284000 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
If your timestamp string is in seconds, then use setSeconds:
var t = new Date();
t.setSeconds( 1370001284 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
Looks like you might want the ISO format so that you can retain the timezone.
var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds
var t = new Date(time_to_show * 1000);
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);
document.write(formatted);
The /Date(ms + timezone)/ is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.
If using react:
import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';
then:
<td><Moment unix>{1370001284}</Moment></td>
Import moment js:
var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");
if you're using React I found 'react-moment' library more easy to handle for Front-End related tasks, just import <Moment> component and add unix prop:
import Moment from 'react-moment'
// get date variable
const {date} = this.props
<Moment unix>{date}</Moment>
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
for people as dumb as myself, my date was in linux epoch
but it was a string instead of an integer, and that's why i was getting
RangeError: Date value out of bounds
so if you are getting the epoch from an api, parseInt it first
var dateTime = new Date(parseInt(1370001284000));
dateTime.toISOString();

how can change the text string to date object?

i am getting string from server and i need to covert that fetching string in to new date object.. for doing this, i tried this function, but no use, any one can help me to convert strings to date object?
my code is :
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.71417&lan=74.00639',
getLondonLocalTime : 'getTime.php?lat=51.5&lan=0.1166667',
getChennaiLocalTime : 'getTime.php?lat=13.0833333&lan=80.2833333',
getBangaloreLocalTime:'getTime.php?lat=12.9833333&lan=77.5833333'
}
$.each(nationZone , function(key, value){
$.get(value, function(response){
var newdate = $(response).find('localtime').text();
if(key == "getNewYorkLocalTime"){
var newyourktime = new Date(newdate);
newyourktime.getTime()
}
});
});
but, the newyourktime is showing local time only.. any help please? as well i am getting the response from server is : 17 Nov 2011 18:09:47 - like this.
Use http://www.datejs.com/
As an example:
var newyourktime = Date.parse('2011-11-11, 11:11 AM');
alert(newyourktime.toString('dd/mm/yyyy HH:mm:ss EST'));
Check out the Datejs library documentation to meet your requirements, after your date string is parsed, you can do a lot with it.
This will try to parse the date using the client machine own local settings, which is not good.
Instead of passing it as string, pass it as the total seconds that passed since 1/1/1970 at midnight and use this number when constructing the new Date object of JavaScript.
For example pass this number: 1321614000000 and you will get November 18th 2011, 1 PM
You could use substr
day = newdate.substr(0,2);
month = newdate.substr(3,3);
year = newdate.substr(7,4);
var newyorktime = new Date(year, month, day);
Substr

Categories