How to get specific date and time string from big string - javascript

i want to get date and time from this kind of timestamp string
var t = "2017-10-28 10:46:20".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
console.log(d);
I want my desired result to be like below :
Sat Oct 28 2017 at 10:46 am

You could do this in vanilla js however I would use the Moment library which makes working with any type of date formatting super simple.
In your example you would just need to do this
const timeStamp = '2017-10-28 10:46:20';
const date = moment(timeStamp).format('ddd MMM do YYYY [at] HH:mm:ss A');
//date => 'Sat Oct 2017 at 10:46:20 AM'

Related

How do I parse the output of `date -u` (unix date command, UTC) using moment.js?

I literally just noticed that the unix date command does not output iso8601 or RFC2822 format dates. 🙁
I've got some input json documents with the date specified as the output of unix date -u, e.g.: Mon Oct 22 04:08:48 UTC 2018. My dates are always in UTC because they were generated with date -u. (Next time I'll be smart and just use date -u +"%Y-%m-%dT%H:%M:%SZ" to get an iso8601 date.)
I've scoured the documentation for parsing and searched the web thoroughly, but can't figure out what I'm doing wrong.
I am trying to parse these using moment.js:
const instr = 'Mon Oct 22 03:53:08 UTC 2018';
const dateFormatString = "ddd MMM DD HH:mm:ss [UTC] GGGG";
const parsedDate = moment.utc(instr, dateFormatString, true);
It's still just giving me:
moment.invalid(/* Mon Oct 22 03:53:08 UTC 2018 */)
What am I doing wrong?
Example:
https://jsfiddle.net/1c3g0r4j/
var parseString = 'Mon Oct 22 03:53:08 UTC 2018';
var formatString = 'ddd MMM DD HH:mm:ss [UTC] gggg';
var locale = 'en';
var strictParse = true;
var parsed = moment.utc(parseString, formatString, locale, strictParse);
alert(parsed.isValid()) //false
Mark Meyer above provides us with the solution, which appears to be using the locale-specific year token YYYY.
var parseString = 'Mon Oct 22 03:53:08 UTC 2018';
var formatString = 'ddd MMM DD HH:mm:ss [UTC] YYYY';
var locale = 'en';
var strictParse = true;
var parsed = moment.utc(parseString, formatString, locale, strictParse);
alert(parsed.isValid())
alert(parsed.toISOString())

Converting a UTC date string to another timezone maintaining the same format

I'd like to convert a UTC date string into the current users timezone and maintain the format of the date string.
For example, I have this code which works:
var data = '2017-04-24 12:06:37';
var date = new Date(data+' UTC');
console.log(date.toString()); // logs "Mon Apr 24 2017 08:06:37 GMT-0400 (Eastern Daylight Time)"
How do I get this to output the new date string in the exact same format dynamically?
You have to add UTC to the string before you convert it to a date.
To convert any date to a UTC string, you can use
var UTCstring = (new Date()).toUTCString();
See my snippet. It compares the five different methods.
var date = new Date('2017-04-24 12:06:37 PM UTC');
var local = date.toString();
var utc = date.toUTCString();
var iso = date.toISOString();
var dateString = date.toDateString();
console.log(date);
console.log(local);
console.log(utc);
console.log(iso);
console.log(dateString);
Solution I used with momentjs:
moment.utc(value).local().format('YYYY-MM-DD HH:mm:ss');

Easiest way to create a javascript date from "18th apr 2011" / "1st jun 1980" format

This works:
var myDateString = '19th sep 2015';
myDateString = myDateString.replace('st','');
myDateString = myDateString.replace('th','');
myDateString = myDateString.replace('nd','');
myDateString = myDateString.replace('rd','');
var date = new Date(myDateString);
But is there a cleaner way? Can I pass the date format (including the ordinal part) to the Date constuctor?
I wouldn't rely on it parsing correctly for all people - for instance, people in France might have their locale set to French (surprise) and that would fail to parse apr for instance, because for them it's avr.
Instead, parse it yourself:
var myDateString = '19th sep 2015';
var parts = myDateString.split(" ");
var date = parts[0].replace(/\D/g,''); // keep only numbers
var month = "janfebmaraprmayjunjulaugsepoctnovdec".indexOf(parts[1].toLowerCase())/3;
var year = parts[2];
var date = new Date(year, month, date);
// note because of how we got the month, it's already conveniently zero-based
Use Moment.js library and use your date string like this:
moment('19th sep 2015', 'Do MMMM YYYY').format("D MMMM YYYY")
Output:
"19 September 2015"
The easiest way is to use a library like moment.js or the date part of sugar.js.
To do this properly by hand is not fun.
Update
If you're in full control of the dates, just use ISO 8601 date format, which the constructor of Date understands in any browser.

converting date into timestamp

I have date like this 25. 02. 2014 18:48:21 and I'm trying to convert it into timestamp
var someDate = '25. 02. 2014 18:48:21';
var timestamp = new Date(someDate).getTime();
but it's returning NaN since I moved files to a new domain, what can be a problem?
'25. 02. 2014 18:48:21' is not a valid date format. You'll have to convert it with regex first, like that:
var someDate = '25. 02. 2014 18:48:21';
var converted = someDate.replace(/^(\d{2}\. )(\d{2}\. )(\d{4})/, '$3. $2$1');
// converted is in format: YYYY. MM. DD.
var timestamp = new Date(converted).getTime();
Running this within the console, creating a new date with that variable gives me Invalid Date. Trying switching around the 25. and 02. like so:
var someDate = '02. 25. 2014 18:48:21';
var timestamp = new Date(someDate).getTime(); // 1393372101000
The format should be "Month, Day, Year, Time".
Switching month and day will work. I also removed the dots.
var date = "25. 02. 2014 18:48:21";
new Date(date.replace(/(\d{2})\. (\d{2})\./, '$2 $1'))
// Tue Feb 25 2014 18:48:21 GMT+0100 (W. Europe Standard Time)
you can try something like below (if your string has always same format)
var someDate = '25. 02. 2014 18:48:21';
var arr = someDate.split(' ');
var time = arr[3].split(':');
var timeStamp = new Date(arr[2],arr[1].split('.')[0],arr[0].split('.')[0],time [0],time[1],time[2]).getTime();
It uses javascript date object constructor
var d = new Date(year, month, day, hour, minute, seconds);
which works across all browsers
function convertSomeDate(str){
var d= str.match(/\d+/g),
dA= [d[2], '-', d[1], '-', d[0], 'T', d[3], ':', d[4], ':', d[5], 'Z'].join('');
return +new Date(dA)
}
var someDate= '25. 02. 2014 18:48:21';
convertSomeDate(someDate)
/* returned value: (Number)
1393354101000
*/

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Categories