How to manipulate date time using vanilla javascript - javascript

I want to manipulate date which come from the api.
When I use: console.log(dataAPI.dateStation)
I see 2023-01-24T06:00:00.000Z
Is there way to change the date time in this format 2023-01-24 06:00:00
Just I want to remove T character between date and time and remove .000Z at the end.

The simplest way to do it is probably:
new Date(dataAPI.dateStation).toLocaleString()
If what you want is to display it somewhere, it'll automatically adapt the ISO date you have into a localized and readable date (based on timezone and language).
To know more about it and the options, here is the doc: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

If you want to print the date in ISO 8601 format, you can use the 'sv' (Sweden) locale and Date.toLocaleString().
You can also specify whichever IANA timezone you wish to use, I'm using UTC in this case.
const d = '2023-01-24T06:00:00.000Z'
let timestamp = new Date(d).toLocaleString('sv', { timeZone: 'UTC' });
console.log('Timestamp:', timestamp);

Use the javascript date class with toLocaleString
new Date(dataAPI.dateStation).toLocaleString('en-US');

Without installing some third-party library, your best bet is probably to use the string you have (which is the format returned by toISOString() ),and modify it as desired. If it's already a string in the format you gave, you can just call replace on it:
dataAPI.dateStation.replace('T',' ').replace('.00Z','')
If it's a Date object, first call toISOString() to get a string:
dataAPI.dateStation.toISOString().replace('T',' ').replace('.00Z','')
If it's a string in a possibly-different format, call new Date() to get a Date object, then call toISOString() on that, and finally call replace on the result:
new Date(dataAPI.dateStation).toISOString().replace('T',' ').replace('.00Z','')

You can use regular expressions to remove the parts you don't want:
let s = "2023-01-24T06:00:00.000Z"
s = s.replace(/T/, ' ')
s = s.replace(/\.\d{3}Z$/, '')
console.log(s)

Related

How to add time zone to specific format in momentjs?

I am trying to get specific format of datetime with time zone
i am getting string of time format which is shown below
var dateTime = "2020-06-01T01:50:57.000Z CDT"
I need to convert the format in to
const offsetTime = moment(date).add("-0.00", 'hours')
const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
Required output
(1:50 AM CDT)
Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs
In simple way to say
YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
and if the string contains only 2 character like "CT" instead of CDT how to capture that.
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')
More documentation here momentJS
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format
var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Your date string is in ISO format with the 'Z' after seconds indicating that it is in UTC time. I am assuming that the 'CDT' is placed in the string in order to indicate which time zone this should be converted to. If you have control over how this string is represented then I recommend changing it so that you indicate the desired timezone elsewhere and simply store the date in UTC format. This way you can initialize a date or moment object with the ISO string as follows:
var date = moment("2020-06-01T01:50:57.000Z")
It is inconvenient the way it is currently since you cannot initialize it this way:
var date = moment("2020-06-01T01:50:57.000Z CDT")
The only option for handling the date in its current form is to parse it. You can do that like this:
var dateTime = "2020-06-01T01:50:57.000Z CDT"
var trimmed = dateTime.trim() // remove leading and trailing whitespace
var isoString = trimmed.substr(0, trimmed.indexOf(' '))
Which will produce the following string
2020-06-01T01:50:57.000Z
You can use that string I called "isoString" to initialize a date or moment object. The next obstacle is to handle converting that UTC string to a certain timezone (in this case CDT). It is simple if you want to convert the UTC date to the current users timezone since that will happen automatically when you initialize the moment or date object with the ISO date string. Otherwise, you need some way to get the timezone from 'CDT' into the format moment wants which was shown by #vjr12 ("America/Chicago"). The only way to do this is to either store that with the date string or create a mapping. It is much easier to convert from "America/Chicago" to "CDT" than it is to convert from "CDT" to "America/Chicago". Your only option with the current form is to create your own mapping from "CDT" to "America/Chicago". You could do something like:
let tzMap = new Map()
tzMap.set('CDT','America/Chicago')
// Set the rest of your timezones
You would need to do that for all timezones and then you could use the timezone parsed from your date string like this:
var tzAbbr = trimmed.substr(trimmed.indexOf(' ') + 1)
which will grab the "CDT" or "CT" for that matter. Then you could use your mapping like this:
var timezone = tzMap.get(tzAbbr)
timezone will be "America/Chicago" in this case and then you can use #vjr12 solution from here to get the form you want.
Note
I highly recommend that (if you are able) to change the current format of the datestring that you are using. The purpose of using UTC time is to be timezone agnostic so it does not make sense to store the timezone with the UTC string. If you want to preserve the timezone then you would be better off using a format which already embeds the timezone.

Date ISO date string issue

console.log(new Date('2016-05-24').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/26/2016').toISOString()); // '2016-05-23T23:00:00.000Z' // why?
I am sending data to the server to parse and want to ensure that server will encode my date correctly.
What is the simplest way to convert date to string as '2016-05-24T00:00:00.000Z' in both cases?
Thanks
console.log(new Date('2016-05-24 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/24/2016 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
Append the timezone to the date before creating a new date object so that the string parsing code in the Date constructor doesn't get confused. Always disambiguate if possible.
Your code was using different timezones for each parse because of the way the dates were formatted. One was using +0 timezone, other was using -1 timezone hence the date being pulled back an hour when the ISO string was created.
One is parsing in UTC time, one is parsing in local time.
new Date('2016-05-24').toISOString() // '2016-05-24T00:00:00.000Z'
new Date('05/24/2016').toISOString() // '2016-05-24T07:00:00.000Z'
Playing around, here's one solution:
new Date(new Date('05/24/2016') - (new Date()).getTimezoneOffset() * 60000).toISOString() // '2016-05-24T00:00:00.000Z'
The strategy:
Create the new offset date
Subtract the offset
Create a new date from that result
Reference links:
javascript toISOString() ignores timezone offset
Why does Date.parse give incorrect results?
On further consideration, I'd recommend parsing the date string into something that is "universal" before passing it to the date constructor. Something like:
var tmp = ('05/24/2016').split('//');
var universal = [tmp[2], tmp[0], tmp[1]].join('-'); // 2016-05-24
...
Also, Moment.js does this sort of thing very neatly.
Use the getDate(), getMonth() and getFullYear() methods to strip out what you need.

Convert string to ISODate

How could I convert the string "2015-02-02" to ISODate 2015-02-02T00:00:00.000Z? I was trying to find some example but did not.
You can use the regular Javascript date functionality for this
new Date(dateString).toISOString()
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
However, date parsing is very inconsistent across browsers so if you need this to be robust I would look into parsing using for example with Moment.js as this will allow you to specify a format string by which the date should be parsed like such
date = moment("12-25-1995", "YYYY-MM-DD");
date.format(); //will return an ISO representation of the date
from: http://momentjs.com/docs/#/parsing/string/
To change "2015-02-02" to "2015-02-02T00:00:00.000Z" simply append "T00:00:00.000Z":
console.log('2015-02-02' + 'T00:00:00.000Z');
Parsing to a Date and calling toISOString will fail in browsers that don't correctly parse ISO dates and those that don't have toISOString.
new Date("2015-02-02").toISOString()
new Date("11/11/2019").toISOString()
or use it as a variable
mydate = "11/11/2019"
new Date(mydate).toISOString()

Moment.js transform to date object

Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.
Example:
var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().
Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().
Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:
momentObj.format("YYYY-MM-DD HH:mm:ss")
Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.
A couple of other little things:
While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.
.toDate did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date();
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);
This will give you a javascript date object with the converted time
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
nice and clean!!!!
I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.
I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.
The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
try (without format step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");
console.log( new Date(d) );
console.log( new Date(moment()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
moment has updated the js lib as of 06/2018.
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.
new Date(moment()) - could give error while exporting the data column in excel
use
moment.toDate() - doesn't give error or make exported file corrupt

Is there a built-in JavaScript function to process a time string?

To make a time like "2009-05-02 00:00:00" to "2009-05-02".
I know I can achieve this by a regular expression, but is there a built-in function that can do this?
There's no built-in date function that can do that. As a matter of fact if you create a new Date object in JavaScript with that date format, you get an Invalid Date Error.
You are correct in using a regular expression or string manipulation in this case.
Here's a list of all the JavaScript Date Functions.
To simply get the date portion of the string and display it without converting into a Date Object. You can simply do this:
var dateString = "2009-05-02 00:00:00"
alert(dateString.substring(0,10)); // Will show "2009-05-02"
To convert this string into a proper JavaScript Date Object, you can use this snippet:
function sqlTimeStampToDate(timestamp) {
// This function parses SQL datetime string and returns a JavaScript Date object
// The input has to be in this format: 2007-06-05 15:26:02
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
The format will be "ddd MMM dd YYYY hh:mm:ss" + TimeOffSet, but you will be able to use any of the standard JavaScript date functions.
See below for two simple methods to get a date format of "2009-05-02", from the initial format, that is "2009-05-02 00:00:00".
<script type="text/javascript">
var mydate, newdate1, newdate2;
mydate = "2009-05-02 00:00:00";
newdate1 = (mydate.split(/ /))[0];
alert('newdate 1: ' + newdate1);
newdate2 = mydate.substr(0,10);
alert('newdate 2: ' + newdate2);
</script>
You might find this helpful:
Return today's date and time
How to use the Date() method to get today's date.
getTime()
Use getTime() to calculate the years since 1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
This is copy-paste from www.w3schools.com since I can't post a link to it...
Or just search Google for "JavaScript date function" or related. Regular expressions are used to match specific parts of strings, which is useful in searching, extraction and replacement, not really anything that would help you with formatting a date.

Categories

Resources